I am trying to get product id from url using match.params.id to pass into api call but its giving error, match returns undefined is use match?.params?.id
Cannot read property 'params' of undefined
App.js
<Router>
<Switch>
<Route path={process.env.PUBLIC_URL +"/images/upload/:id"}>
<UploadImages />
</Route>
</Switch>
</Router>
Redirect:
//params.id from material-ui datagrid table
<LinkContainer to={`/admin-panel/home/images/upload/${params.id}`}>
<button className="btn btn-primary mr-2">Set Images</button>
</LinkContainer>
const columns = [
{ field: '_id', headerName: 'ID', width: 250 },
{ field: 'name', headerName: 'Product Name', width: 300 },
{ field: 'price', headerName: 'Price', width: 130 },
{ field: 'countInStock', headerName: 'Count In Stock', width: 230 },
{ field: 'createdAt', headerName: 'Date Created', width: 230 },
{
field: 'action',
headerName: 'Action',
width: 350,
renderCell: (params)=>{
return (
<div>
<LinkContainer to={`/admin-panel/home/product/${params.id}/edit`}>
<button className="btn btn-info mr-2">Edit</button>
</LinkContainer>
<LinkContainer to={`/images/upload/${params.id}`}>
<button className="btn btn-primary mr-2">Set Images</button>
</LinkContainer>
<Button className="btn btn-danger" onClick={()=>deleteHandler(params.id)} ><Delete /></Button>
</div>
)
}
},
];
return (
<div className="productList" style={{height:600}} >
{loading ? (<Loader />) : error ? (<Message variant="danger" >{error}</Message>):(
<DataGrid
rows={products}
columns={columns}
pageSize={10}
rowsPerPageOptions={[5]}
checkboxSelection
/>
)}
</div>
)
}
UploadImages.js
function UploadImages({ location, match, history }) {
const productID = match.params.id
return (<div></div>);
};
export default UploadImages
Id is passed in URL
http://localhost:3000/images/upload/61555780c208142757be70v1
Initially when the component is loaded, params is not undefined.
Please do this...
const productID = match && match.params && match.params.id;
What you are doing above is this:
You are telling reactjs to only assign productID a value after doing the sanity checks on the right-side.
A clue into this error:
Cannot read property 'params' of undefined
It is telling you that you are attempting to pick a key called param from an undefined variable (in this case match).
So the sanity check above means that you are telling reactjs to only attempt picking param if match is defined; and only attempt to pick id if param is defined.
Writing match?.params?.id is the quickest solution