I’m building an online shop with React. I can’t get the item details to show up on my local server. The backend seems fine, but the frontend isn’t cooperating. I tried using the useparams hook, but it’s giving me an ‘undefined params’ error.
Here’s a simplified version of what I’m working with:
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchItemInfo } from './itemActions';
const ItemPage = ({ match }) => {
const dispatch = useDispatch();
const { item, isLoading, error } = useSelector(state => state.itemInfo);
React.useEffect(() => {
if (match?.params?.id) {
dispatch(fetchItemInfo(match.params.id));
}
}, [dispatch, match]);
return (
<div>
<h2>{item?.title}</h2>
</div>
);
};
export default ItemPage;
My action file looks something like this:
import axios from 'axios';
import { ITEM_REQUEST, ITEM_SUCCESS, ITEM_FAIL } from './constants';
export const fetchItemInfo = (id) => async (dispatch) => {
try {
dispatch({ type: ITEM_REQUEST });
const response = await axios.get(`/api/items/${id}`);
dispatch({ type: ITEM_SUCCESS, payload: response.data });
} catch (error) {
dispatch({ type: ITEM_FAIL, payload: error.message });
}
};
I’ve double-checked my code, but I can’t figure out why the item details aren’t showing up. The weird part is, there are no errors in the console. Any ideas on what I might be missing?
I encountered a similar issue in my project. Have you verified that your Redux store is properly set up and connected to your component? It’s possible the item data isn’t being stored correctly. Try adding some console.log statements in your reducer and action to trace the data flow. Also, ensure your component is wrapped with a Redux Provider. If the data is reaching your store but not rendering, check if your selector is correctly structured. Sometimes, the state shape can be different than expected, causing silent failures in data retrieval.
hey there! have u tried using react router v6? it changes how params work. instead of match.params, u need useParams() hook. like this:
import { useParams } from 'react-router-dom';
const { id } = useParams();
tthen use ‘id’ in ur useEffect. that might fix ur undefined params issue. good luck!
Hey SwimmingCloud!
I’m curious about a few things in your setup. Have you checked if the API is actually returning data? Maybe try logging the response in your fetchItemInfo action before dispatching.
Also, what does your reducer look like? Sometimes the issue can be in how we’re updating the state.
Oh, and I noticed you’re using match.params. Are you using an older version of React Router? If so, have you considered upgrading? The newer versions handle routing a bit differently.
By the way, how are you rendering this ItemPage component? Is it wrapped in a Route component somewhere? That could explain why match isn’t defined.
Let me know what you find out! I’m really interested to see what’s causing this. Debugging can be such a puzzle sometimes, right? 