Hello everyone, I am having an issue with passing data from a json file down to one of my components.
First I get the data from the JSON file in my app.js
It’s trowing an error message from this last step. I’ve doubled checked everything I know of and it’s still not getting where I want it. “TypeError: Cannot read property ‘map’ of undefined”
I know I am dumping a lot of code here, but I am honestly stuck. I’ve been at it a few hours and I’m no closer to solving it.
I thank you in advance, I hope it will only take a few minutes of your time to help me.
You are rendering your components before the data has been fetched, so your component is complaining that it cannot map over something that is still undefined.
A common workaround is to display some UI element while the data is being fetched like a spinner or loader.
In react is pretty trivial:
// in your parent keep track of a loading state
state = {
loading: true,
data: [] // don't know yet
}
// in your child
if(props.loading) { // render spinner }
else { // render list component }
This is just a simple pseudo-code but hope it will help
Thank you. I have been working on this project after 8 hour shifts, so my brain has been a little fried.
Now that I have a day off I can see my errors. Thanks for your help
Here’s the passing from my app.js
I feel bad for not being able to solve this myself with all the help you’ve given me. I really appreciate your expertise.
when the component rendered, call componentDidMount (cDM).
inside cDM you can call an async function when it is done, set the loading to false.
render the data you got from cDM.
your code will always show the loading text since after it was rendered, React will call cDM and you set the loading state to true, so it will always show loading text.
After working (pretty much all day ) I think I have found the main problem .
After console.log-ing everything, I found that my main retrieval component is returning undefined.
I am betting that there’s a beginner’s mistake here, I just can’t see it yet.
I feel like I am on the home stretch, after this I can finally stop asking for help!
Sorry about these delays. I’ve been getting called in to work a lot because of this whole pandemic thing.
This is the full component. The main problem is the fetch is not getting the data from the JSON file.
From what I can tell it is passing correctly to the component (what I thought was the problem initially).
The error messages are gone, and I managed to get my JSON file to show up in my console with that res.text() line. However now It is still returning undefined when I don’t use the text or when I try to set propdata to the value of text Or Res.