Reputation: 29
I want to use useParams
inside of useEffect
but I am getting error saying that "Uncaught TypeError: Cannot read properties of undefined (reading 'params')".
app.js
<Route>
<Route path="/product/:id" element={<ProductDetails />} />
</Route>
ProductDetails.js
const dispatch = useDispatch();
const { id } = useParams();
useEffect(() => {
dispatch(getProductDetails(match.params.id));
}, [dispatch, match.params.id]);`
It is giving me error as I have mentioned above.
Upvotes: 0
Views: 1219
Reputation: 203562
It looks like you half converted some code/logic from react-router@5
where there was a match
prop injected into the component to react-router@6
where you instead use the useParams
hook. match
is simply undefined so an error is thrown when attempting to access into it a params
property.
The useParams
hook replaces entirely props.match.params
. The id
route path parameter alone is the dependency now.
const dispatch = useDispatch();
const { id } = useParams();
useEffect(() => {
dispatch(getProductDetails(id));
}, [dispatch, id]);
Upvotes: 1
Reputation: 3609
I don't think you want to use a hook inside of a useEffect function. To answer your question
You could try this
useEffect(() => {
dispatch(getProductDetails(match?.params?.id));
}, [dispatch, match?.params?.id]);`
But you're using javascript not typescript, so you can try this.
const param = match && match.params ? match.params.id : ''
useEffect(() => {
if (param) {
dispatch(getProductDetails(param));
}
}, [dispatch, param]);
Upvotes: 0