What do you do when you are not sure that the object variable has the specific property?
My recent answer is Optional chaining.
What is Optional chaining?
The optional chaining operator (
?.
) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. Optional chaining (?.) - JavaScript | MDN
I just quoted from MDN haha.
It basically makes it easier to access a property within an object.
How does it make React App development easier?
Imagine you fetch the user data from Firebase Authentication.
The user variable will be like this after fetching data.
{ displayName: 'Mike' }
import React from 'react';
// Use Context API and make useStateValue
import { useStateValue } from './context/useStateValue'
function App() {
const [user, dispatch] = useStateValue(null);
return (
<div className="App">
<h1>Welcome, {user.dispayName}</h1>
</div>
);
}
export default App;
What's gonna happen?
TypeError: Cannot read property 'dispayName' of null
Yes, this is what happens.
Conventional way
Trinomial calculus
I always used Trinomial calculus before Optional Chaining in this case.
In this pattern, your React app renders <div>Loading…</div>
initially and then show <h1>Welcome, Your Name</h1>
after fetching data from Firebase.
I kinda like this because <h1>
doesn't get rendered until it's needed to be rendered.
{user ? <h1>Welcome, {user.dispayName}</h1> : <div>Loading…</div>}
Nullish coalescing Operator
<h1>Welcome, {user && user.dispayName}</h1>
Use Optional chaining
Just adding one ?
! Deadly simple, isn't it!?
<h1>Welcome, {user?.dispayName}</h1>
Conclusion
I think most of the time Optional chaining is very handy and speeds up your development.
Count on Trinomial calculus when you need to show other elements while the object or property is not valid.
Top comments (6)
would have never considered what I was doing "trinomial calculus" 😆
Is this a typo? Surely the author meant "ternary operator" unless I am completely out of the loop.
I mean I suppose you can think of the left of the ? as predicate logic and binary output from the predicate output... or something like that lmao
In this way, there will be no error thrown certainly. But there will be
Welcome,
printed.A better way could be to be add a default name with ??
Welcome, {user?.dispayName??'Taishi'}
If
user
isnull
, then<h1>Welcome, {user?.dispayName}</h1>
will render to<h1>Welcome,</h1>
, thoughFWIW this is called null propogating operator in .NET. And I've been awaiting a (near) js equivalent. Thanks for the heads up!