progpro
progpro

Reputation: 195

How to render array of objects in javascript react if its undefined?

I want to check for the empty array in react JavaScript. But when I am using the question mark for checking that is it undefined or not then the react and is crashing.

I am using something like this:

const [verlist, setverlist] = useState([]);

In the useEffect hook I'm using setverlist(response.versions.version). Here versions is object. And in it version is an array of objects.

But when I get versions as empty object {}, my react app crashes because in console I'm getting undefined.

I'm rendering like this:

{[...verlist].reverse().map((value, id) => {})}

How do I fix this ?

Upvotes: 1

Views: 425

Answers (3)

Alak
Alak

Reputation: 122

You can put a check in front of your code.

verlist && verlist.length > 0 && [...verlist].reverse().map((value, id) => {})

Let me know if it works.

Upvotes: 1

Mykyta Halchenko
Mykyta Halchenko

Reputation: 798

If verlist is an array and can be undefined, try:

verlist && verlist.length && [...verlist].reverse().map((value, id) => {})

Upvotes: 0

Raphael Ben Hamo
Raphael Ben Hamo

Reputation: 166

Change

from : [...verlist].reverse().map((value, id) => {})

to: verlist.length > 0 && [...verlist].reverse().map((value, id) => {})

Upvotes: 0

Related Questions