0

When following this documentation https://reactjs.org/docs/faq-ajax.html I run the code and if i console.log() the items variable in the return statement. I get the following which causes issues because the first response is empty: enter image description here

The code i used is the following:

import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
     
          setItems(result); 
        },
    // Note: it's important to handle errors here
    // instead of a catch() block so that we don't swallow
    // exceptions from actual bugs in components.
    (error) => {
      setIsLoaded(true);
      setError(error);
    }
  )
  }, [])


  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {console.log(items)}
    </ul>
    );
  }
}

export default App;

Any help would be great.

2 Answers 2

2

It's not 'first response is empty' issue. First console.log runs before the async code executes, when async code executes and you change your state, component rerenders and reruns the console.log with newly updated items that are now filled with data fetched from api.

Perhaps you should read a bit more about react component lifecycles :)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a conditional to run your code only if result is not empty to avoid crashing.

if (result) { 
   //your code
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.