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 ?
Advertisement
Answer
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.