1

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 ?

1
  • is verlist an array or object? because you said: 'But when I get versions as empty object {}' Commented Aug 10, 2022 at 9:18

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Change

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

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

2 Comments

The app is again crashing
Can u add the whole page?
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.