Home > Software design >  React API call returns empty response then returns the data
React API call returns empty response then returns the data

Time:10-14

When following this documentation 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.

CodePudding user response:

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 :)

CodePudding user response:

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

if (result) { 
   //your code
}
  • Related