Home > Mobile >  I am losing my api data when I refresh my react app
I am losing my api data when I refresh my react app

Time:09-28

I am using axios to fetch and retrieve data from an api. I then set the api data to some state. When I save the changes, it shows the name from index [0] of the array, as I want. However when I refresh the page, it throws an error "Cannot read properties of undefined (reading 'name')". It seems like I am losing the api data when I refresh, what am I doing wrong here? The api endpoint is madeup, as I don't want to share the real endpoint here.

const [apiData, setApiData] = useState([]);

  useEffect(() => {
    axios
      .get("https://some-api")
      .then((res) => {
        setApiData(res.data);
      })
      .catch((error) => {
        alert(error.message);
      });
  }, []);

return <h1>{apiData[0].name}</h1>

CodePudding user response:

try it please

return <h1>{ aapiData.length && apiData[0]?.name}</h1>

CodePudding user response:

It has nothing to do with refreshing the page. This will always happen on the first render for this component.

The initial state value is an empty array:

const [apiData, setApiData] = useState([]);

And you're trying to access the first element of that array:

return <h1>{apiData[0].name}</h1>

An empty array has no first element, so it throws an error.

You can use optional chaining:

return <h1>{apiData[0]?.name}</h1>

Or perhaps check if it's there before using it:

return <h1>{apiData[0] && apiData[0].name}</h1>

Or not render anything at all if the array is empty:

return apiData.length > 0 ? <h1>{apiData[0].name}</h1> : null;
  • Related