Reputation: 857
I have the following code in a product, js, I'm trying to return a single item on API call using the id param. When I run I get props not defined. I don't know how to solve this
import React, {useEffect }from 'react';
import { detailsProduct } from '../actions/productActions';
function Productscreen(props) {
const productDetails = useSelector(state => state.productDetails);
const {product , loading, error } = productDetails;
const dispatch = useDispatch();
useEffect(() => {
dispatch(detailsProduct(props.match.params.id));
return () => {
//
}
}, [])
Upvotes: 3
Views: 3466
Reputation: 161
The way you pass the component to your route matters. To have access to match, you would have needed the render prop to destructure the match.
<Route path='/whatever/:id' render={({match}) => <Productscreen match={match} />} />
You can also use the new react router hooks useParams, I prefer them, mostly because of Typescript.
import React, {useEffect } from 'react';
import { detailsProduct } from '../actions/productActions';
import { useParams } from "react-router-dom";
function Productscreen() {
const productDetails = useSelector(state => state.productDetails);
const {product , loading, error } = productDetails;
let { id } = useParams()
const dispatch = useDispatch();
useEffect(() => {
dispatch(detailsProduct(id));`
return () => {
//
}
}, [])
}
in that case, your route should be:
<Route path="/whateverpath/:id">
<Productscreen/>
</Route>
Upvotes: 1