Reputation: 802
<Route exact path="/product/:id" element={<ProductPage />} prod_id={this.id}/>
Here i have a route what my intension is to get the the id of the path in my component so that i can fire the function and get the details of the product
obviously prod_id={this.id}
is not working for me and also supposed to not work writing this is intention just to show what i am thinking
once i get this id in my component i can fire this function
export const getSingle=(id) => async(dispatch)=>{
try {
dispatch({type:SINGLE_PRODUCT_REQUEST})
const {data} = await axios.get(`/api/v1/products/detail:${id}`)
dispatch({
type:SINGLE_PRODUCT_SUCCESS,
payload:data,
})
} catch (error) {
dispatch({
type:SINGLE_PRODUCT_FAIL,
payload:error.response.data.message,
})
}
}
to get the product detail and fill the required field
Upvotes: 1
Views: 440
Reputation: 2799
You cant pass props to Route and access them in target component. This is not how things in React work.
If you want to access params from URL, you can use hooks - useParams()
export const getSingle= () => async(dispatch)=>{
try {
dispatch({type:SINGLE_PRODUCT_REQUEST})
const params: { id: string } = useParams();
const {data} = await axios.get(`/api/v1/products/detail:${params.id}`)
dispatch({
type:SINGLE_PRODUCT_SUCCESS,
payload:data,
})
} catch (error) {
dispatch({
type:SINGLE_PRODUCT_FAIL,
payload:error.response.data.message,
})
}
}
For non functional component, you have to access params from props
class Example extends Component {
render() {
const { id } = this.props.match.params;
return (
<div>ID : { id }</div>
);
}
}
Upvotes: 1
Reputation: 41
you can get id
from useParams()
hook.
Route code
<Route exact path="/product/:id" element={<ProductPage />} />
in react component, import useParams
hook from react-router-dom
and get id using
let { id } = useParams();
Upvotes: 2