I’m using React Router v6 in my React app, and I have a Category page that works fine when navigating within the app. However, when I refresh the page or paste the URL into a new tab, I get the following error:
TypeError: Cannot read properties of undefined (reading ‘id’)
at Product (http://localhost:3000/static/js/bundle.js:6946:59)
This happens because the currentCategory is undefined before it is loaded, so when React tries to map over currentCategory.products, it throws an error.
This is my Category component:
export const Category = () => {
const { id } = useParams<{ id: string }>();
const location = useLocation();
const { currentCategory, setCurrentCategory, fetchCategoryById, loading } = useCategoriesContext();
const hasFetched = useRef(false);
useEffect(() => {
if (location.state?.category) {
setCurrentCategory(location.state.category);
} else if (id && !hasFetched.current) {
hasFetched.current = true;
console.log(typeof Number(id), 'typeof id')
fetchCategoryById(Number(id));
}
}, [id, setCurrentCategory, fetchCategoryById, location.state]);
if (loading) return <p>Loading...</p>;
if (!currentCategory) {
return <p>404 Error, Category Not Found</p>;
}
return (
<div>
<h1>{currentCategory.name}</h1>
<ul>
{currentCategory.products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
};
Question
How can I ensure that the currentCategory is fetched properly when the user refreshes the page or pastes the URL into a new tab, so the page does not crash?
Expected Behavior
The category page should load correctly whether I navigate to it within the app or refresh the page.
If the category is not found, a “404 Error” message should be displayed instead of crashing.
Actual Behavior
Navigating within the app works fine.
Refreshing the page or pasting the URL causes an error because currentCategory is undefined before the API fetch completes.
What I’ve Tried
Checking if currentCategory exists before rendering.
Ensuring fetchCategoryById(id) runs when location.state.category is not available.
Wrapping currentCategory.products.map() in a conditional to prevent mapping over undefined.
I have checked the id from the useParams and its working correctly.
I have another component doing the exact same and this works fine.