DEV Community

Nwanguma Victor
Nwanguma Victor

Posted on • Updated on

Avoid unnecessary errors when conditionally rendering in React with "Optional Chaining."

Introduction

When I started learning React and Javascript I would run into errors because I would be trying to access an object property or data from an async API function call that has not been loaded.

Statement of Problem

From the example below React would throw an error, because you are trying to access an object property that has not been loaded from the API call

import React, {useState, useEffect} from 'react'

export default function App () {
// STATE
const [state, setState] = useState({})

// ONMOUNT
useEffect( async ()=>{
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => setState(json) )
}, [])

return ( 
<div>
{ state.title && 
    <div>
      ...
    </div>
}
</div>
)}
Enter fullscreen mode Exit fullscreen mode

Proposed Solution

Optional Chaining

The optional chaining operator (?.) allows you to read the value of a property deep in a chain of related objects without having to validate each reference in the chain.

The ?. operator is similar to the . chaining operator, except that instead of throwing an error if a reference is null (null or undefined), the expression short-circuits with an undefined return value.
It returns undefined when used with function calls if the specified function does not exist.

With Optional Chaining the example above would be rewritten to:

import React, {useState, useEffect} from 'react'

export default function App () {
// STATE
const [state, setState] = useState({})

// ONMOUNT
useEffect( async ()=>{
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => setState(json) )
}, [])

return ( 
<div>
{ state?.title && 
    <div>
      ...
    </div>
}
</div>
)}
Enter fullscreen mode Exit fullscreen mode

Advantages of Optional Chaining

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

Conclusion

  1. Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.

  2. Optional chaining with function calls: When attempting to call a method that may or may not exist, you can utilize optional chaining. This can be useful, for example, when utilizing an API when a method is unavailable.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

let result = someInterface.customMethod?.();
Enter fullscreen mode Exit fullscreen mode

Refrences

Optional chaining (?.)

Top comments (0)