Skip to content
Advertisement

Fetching JSON and rendering it with react

My fetch gives me the following JSON:

“{“name”:”John”,”age”:26,”city”:”London”}”

However when i try to render it on my page like this:

JavaScript

I get a TypeError: Cannot read property ‘map’ of undefined

How can i fix this?

Thanks in advance!

Advertisement

Answer

Given that the API response is {"name":"John","age":26,"city":"London"} then I suggest the following:

  1. Save the entire response result into state. Use a catch block to catch any errors and set any error state, and use a finally block to set the loading state (more DRY).

    JavaScript
  2. Render from state, no array, just the state fields.

    JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement