React pass using useNavigate cannot read properties of null

Viewed 251

I'm using useNavigate to pass data between components.

import { useNavigate } from "react-router-dom";

function Categories() {
const navigate = useNavigate();
.
.
onClick={() => navigate("/books", {state:{ name: categorie.name }})}

Then I resive the data from second component

import {useLocation} from "react-router-dom";
function Books() {
const location = useLocation();
let currentcategory = location.state.name;

Its works fine but If I try to access directly using URL https://localhost/books

I got this error

Uncaught TypeError: Cannot read properties of null (reading 'name')
2 Answers

you need to destructure it

const {state} = useLocation();
console.log(state)

Issue

The issue is that the route/link/navigate state only exists if you transition from the component providing the state. If you manually enter the receiving route's URL path in the address bar, this state is missing, or undefined/null.

In other words, location.state is undefined/null, and the error is thrown when accessing further into it to get location.state.name.

Solution

Use a null-check/guard-clause or the Optional Chaining operator to defend against the potentially null access, or provide a fallback value to destructure from.

  • Null-check/guard-clause

    const { state } = useLocation();
    const currentCategory = state && state.name;
    
  • Optional Chaining operator

    const { state } = useLocation();
    const currentCategory = state?.name;
    
  • Fallback object to destructure from

    const { state } = useLocation();
    const { name: currentCategory } = state || {};
    
Related