'Changing variable value throughout component when undefined
How can i change a variable that is used all throughout a component when it is undefined? For example:
<div>
<div>{user.name}<div>
<div>{user.id}<div>
<div>
If the state of the user is undefined how can i put another variable in it's place in both(or many) divs?
Solution 1:[1]
So you want to conditionally check if your user object contains valid data; a very common situation which can be resolved with an if check.
Professionally I like to use the nullish coalescing operator, which, as per MDN:
returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
In your code, you would use it like this:
{user.name ?? fallbackVariable}
Solution 2:[2]
Create a variable and then use that where ever you want in the component like below
const userObj = user ?? diffUser
<div>
<div>{userObj?.name}<div>
<div>{userObj?.id}<div>
<div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marco |
| Solution 2 | Murali N |
