Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading