I am getting an error while showcasing single product on screen, the error is stated as-
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'params')
The code which is causing the error is
function ProductScreen({ match }) {
const [product, setProduct] = useState({})
useEffect(() => {
const fetchProduct = async () => {
const { data } = await axios.get(`/api/products/${match.params.id}`)
setProduct(data)
}
fetchProduct()
}, [match])
I guess the error is of match.params.id, But I am having a hard time to resolve the error.Can anyone know the fix to this error?
You passed props into ProductScreen but props.match is undefined.
Try giving props.match a non-empty value then it should work.
Then use other ways like useNavigate hook to access history and navigate. Refer to official Doc. v6.0.2 does not pass history props and in match.params.id, match is undefined and that's why you are getting this error when you are trying to access match.params as undefined can't have a property.
You have to handle it differently.
The above code shows the error- "'data' is not defined.eslintno-undef" and "'data' is declared but its value is never read.ts(6133) "
You are getting this error because, const is block scoped
if (match) {
const { data } = await axios.get(`/api/products/${match.params.id}`)
}
setProduct(data)
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
You can handle it by,
let data;
if (match) {
({ data } = await axios.get(`/api/products/${match.params.id}`))
}
setProduct(data)
I would suggest, you can go through basics for better understanding.