I am having trouble with a little React Router exercise
I have a File "ItemDetail.js" in which i define a Componenet "ItemDetail" which is called by a Route from another Component like so: <Route path="/shop/:id" component={ItemDetail}/>.
This is my code:
import React, {useState, useEffect} from "react";
function ItemDetail({ match }) {
const [item, setItem] = useState({});
console.log(match);
useEffect(() => {
fetchItem();
}, []);
const fetchItem = async () => {
const data = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id=${match.params.id}`);
const item = await data.json();
setItem(item);
console.log(item);
}
return (
<div>
<h3>Item: {item.data.item.name}</h3>
</div>
);
}
export default ItemDetail;
The id of the path is an id that i need for the API call (over match.params.id).
The fetchItem() method fetches the data I need as a JSON, I then save it in the state item and then render my render stuff. But it throws an error with : "TypeError: Cannot read property 'item' of undefined" in the line where i access item.data.name from JSX.
Weird thing is: when I change <h3>Item: {item.data.item.name} </h3> to <h3>Item: </h3> and then back to <h3>Item: {item.data.item.name} </h3> It works, just this one time, and when i refresh or navigate through my site to this path again it throws this error again
itemis only set to{}, which means trying to accessitem.data.itemwill blow up (you'd be trying to accessitemonundefined). One common pattern to avoid this is to have something display while it's loading from thefetchcall:<h3>Item: {item.data ? item.data.item.name : "Loading..."}</h3>fetchhappens asynchronously, so there's definitely a render that happens before the fetch returns and you set state.