Home > other >  Should I map an array if there is only one object in it?
Should I map an array if there is only one object in it?

Time:04-28

I am trying to use data I fetch from an Api in a react project. The api returns an array with only one object, but that object has many properties I need to use in the jsx.

My question is more about efficiency/best practice. Should I map the array or just call index 0.

This is within the return of the component. Just to reiterate the array only has the ONE object which has a bunch of properties.

array.map((obj) => (
   <p>{obj.id}</p>
   <p>{obj.name}</p>
   <p>{obj.other}</p>
   <p>{obj.title}</p>
)) 

or

<p>{array[0].id}</p>
<p>{array[0].name}</p>
<p>{array[0].other}</p>
<p>{array[0].title}</p>

CodePudding user response:

If the API is not going to change, and always return an array with an entry, just set your state accordingly:

fetch('/api')
  .then(response => response.json())
  .then(data => setSomething(data[0]))

If the API can return multiple entries, you will need .map() for semantics.

CodePudding user response:

Calling index 0 would be slightly more performant than starting an iteration, getting the one object, then stopping the iteration. However if you will ever expect there to be more than one object then you will need map.

  • Related