Thursday, December 22, 2022

[FIXED] what is the right way to check that an object is not null in react before assigning one of its properties to a variable

Issue

In React it is very commong that as components get updated objects go from null to their intended content. This is a dynamic process that can create errors everytime you assing a property from those objects to another variable.

Lets say that user is the object that will go from null to the actual user object and that I want to extract the property uid from user:

const uid = user.uid

This can trigger a fatal error in react if user is null when I try to execute this operation.

I have tried to use:

user && const uid = user.uid, but it doesn't work at all.

Would the right way to do this be:

const uid = user && user.uid

any comments/ sugestions?


Solution

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined

So do this

const uid = user?.uid // will be undefined if not there else the actually value


Answered By - carlosdafield
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.