Home > Software engineering >  How do I map through this (file) - React MongoDB Javascript
How do I map through this (file) - React MongoDB Javascript

Time:03-07

enter image description here[I have this saved in a useState saved (just console.logged it) and would like to map it. Somehow my map function doesn't seem to work. Maybe it is the wrong file format or path?

{result.data.data.map((e) => { return (<> <li>{e.charity}</li> </> )})}

CodePudding user response:

You should map like this :

{result.data.data.map(user => <li> {user.charity} </li>)}

user here it each item of your array

CodePudding user response:

There is nothing wrong with your map function. What I assume is happening is you are attempting to map over this array before result becomes available. If you are making an asynchronous api call to receive this data, then the code will continue executing while waiting for the result.

I can't be sure what the rest of your code looks like, but an easy way to fix this is to use optional chaining to call your map.

Something like this:

{result?.data.data.map((e) => { return (<> <li>{e.charity}</li> </> )})}

The addition of the question mark will check if result has any value, and will gracefully exit the execution without throwing an error. Then when the result becomes available, then react will execute the result map.

All this is assuming you are setting up the rest of your component correctly. If this doesn't solve your issue, please update your question to include more relevant code.

  • Related