PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

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

 December 22, 2022     javascript, reactjs, syntax     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing