Home > Mobile >  How to implement error boundaries in react with MERN?
How to implement error boundaries in react with MERN?

Time:07-07

My goal is to simply dynamically present the data from a mongo database of a specific document.

const Details = () => {
    const { id } = useParams()
    const [product, setProduct] = useState(null)

    useEffect(() => {
        const fetchProduct = async () => {
          const response = await fetch(`/api/products/${id}`)
          const json = await response.json()
    
          if (response.ok) {
            setProduct(json)
            console.log(json)
          }
        }
    
        fetchProduct()
      }, [id])

this code works fine as it gets the product, but my problem is occurring with the rendering:

return ( 
        <div className="details">
            <Menu />
            <h1 className="movement">Product Details - {product.name}</h1>

        </div>
     );
}

the error that I'm getting is Uncaught TypeError: Cannot read properties of null (reading 'name') and to Consider adding an error boundary to your tree to customize error handling behavior.

my question being is how do i implement correct error handling

CodePudding user response:

Just use the optional chaining operator:

product?.name

It's typical that in the first render product is not yet available so you cannot access to any of its properties. With the optional chaining operator you are covering this case.

See more: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Optional_chaining

If you want to add Error Boundaries: https://reactjs.org/docs/error-boundaries.html#gatsby-focus-wrapper

CodePudding user response:

React renders the component before you make an api request, thus product doesn't exist (it's null based on how you set its initial value). Then when response is received you set product to state and react re-renders your component. Now product exists.

To solve it, render h1 only when product exist.

<div className="details">
    <Menu />
    { product && <h1 className="movement">Product Details - {product.name}</h1> }
</div>

Also, you can render a message if product is not yet exist

<div className="details">
    <Menu />
    { product && <h1 className="movement">Product Details - {product.name}</h1> }
    { !product && <p>Loading ... </p>
</div>
  • Related