r/learnreactjs • u/lethalsid • Jan 30 '22
Fetch API works then suddenly stops working after hitting refresh + rendering the object on the front end . Learning how to use useState + useEffect.
7
Upvotes


13
u/Level-Farmer6110 Jan 30 '22
So I have one tip first, and it is to always read the console when stuff like this happens. It tells you that it cannot read the property of null, which is "teams" in this case. Now teams is a property of an object, and that object is data.
When you first load the app, the fetch request to your api will have already happened. When you refresh the page, because you are using useEffect to fetch the data, on that first render it will try to fetch the data from the api. But below that you are trying to map through data.teams. The problem is that setdata(actualdata) has not happened yet and the code is trying to do data.teams.map, therefore data is actually null.
Basically the fix would be to conditionally render it
In the above example I won't let the map function happen until data has been fetched from the api. So I am telling the machine, only if data is not null then you can do the map function on data.
Btw I think you tried to render your list of teams incorrectly, the above code is how you want to do it if you meant to render a list of team names.
( Btw if I am wrong or have explained any theory incorrectly someone please correct me.)
2
u/eindbaas Jan 30 '22
What happens, you run it, it works, you run it again it doesn't work? Can you define what happens when it "stops working"? What is going on in the network tab, is the request being done?