React cannot read properties of array undefined while using use location hook

Viewed 45

I am trying to pass some data from one page to the other in react using the useNavigate and useLocation hook.The data is transferring fine and i am recieving it in the next component as shown below:

// sending component
   const handleNavigate = () => {
   navigate('/updateBlogPost', { state: { blogPost } });
};

//recieving component
const location = useLocation();
const [title, setTitle] = useState(location.state.blogPost.title);
const [description, setDescription] = useState(location.state.blogPost.description);
const [categories, setCategories] = useState(location.state.blogPost.categories);
const [content, setContent] = useState(location.state.blogPost.content);

Now I am facing the problem with the category array because it becomes undefined when the page first renders and i get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

I can get rid of the error using optional chaining but how to get the data of the array when it is available. I tried setting it in the use effect but it does not seems to work can any one suggest some better way?

1 Answers

use useEffect to get data when its available based on dependencies of "location" changes everytime it will fire it after every completed render.

const [categories, setCategories] = useState([]);

useEffect(() => {
  if(location.state.blogPost.categories)
     setCategories(location.state.blogPost.categories)
},[location])
Related