So, I've decided to create this blog because I've seen several articles with people experiencing the same issue I dealt with. fetching data with nested objects.
For people new to programming, such as myself, I think we often find ourselves running into hundreds of problems a week as we learn new skills. The most frustrating part about this, at least for myself, is running into an issue you've once resolved. For me, that is this blog topic.
I first ran into this issue during my bootcamp course, but I was able to resolve it fairly quickly(maybe a few hours, up to a day). It was also from a public API. The next time I experienced this issue, the data was created from scratch, and when fetching the data, I would get a response that looks like the following:
When trying to access the data, I often ran into a few recurrent errors. Here are the most frequent ones I've encountered:
- The server would try to identify the "id", and would fail to read it, despite console logging and confirming data being returned is correct.
- The server cannot access the route. Assuming the route is setup correctly, this error occurs because the path to access the route,
http://localhost:3000/data/`${data.id}`
cannot access the id of the data. This would work if there was a numerical value that represents the value in the first image above. The path would look something like
http://localhost:3000/data/0/`${data.id}`
What eventually worked for me, was using the Object.values and data.filter methods. Another important factor I discovered, was knowing how to Google(I'm still not good at it, getting better though). I didn't find a specific article or solution for this problem, I put pieces together from different articles, kept trying until I produced a result that allowed me to keep going. Heres what the code looks like:
useEffect(()=>{
fetch(itemURL)
.then(res => res.json())
.then((allItems) => Object.values(allItems).filter((value)=>{
return setItems(value)
}))
},[])
Although I was able to resolve the issue to an extent, I still am left with questions. How does the data return as nested objects? Is it due to the amount of data being fetched? How can we fetch promise data from nested objects, and access them? Thank you if you read this far. If you have any questions, answers, or input, feel free to reach out. I am always open to learn something new.
Top comments (0)