'match.params.id not working in react router dom
I have installed the latest version of react-router-dom in my project. And it is saying match is undefined. However, it works fine when I use [email protected].
Can anybody tell me how should i change my code to use the match.params.id or what is the substitute method in the latest react-router-dom??
Attached is my code which is working fine in react router dom [email protected].
import React from 'react';
import { useState, useEffect } from 'react';
function ItemDetail({match}) {
const [item, setItem]= useState({});
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError] = useState(false);
useEffect(()=>{
fetchItem();
//console.log(match);
// eslint-disable-next-line react-hooks/exhaustive-deps
},[setItem]);
const fetchItem= async ()=>{
setIsLoading(true);
setHasError(false);
try {
const fetchItem= await fetch(`https://fortnite-api.theapinetwork.com/item/get?id=${match.params.id}`
);
const item1 = await fetchItem.json();
setItem(item1.data.item);
console.log(item);
console.log(item1);
} catch (error) {
setHasError(true);
}
setIsLoading(false);
}
return (
<div >
<h1>{item.name}</h1>
</div>
);
}
export default ItemDetail;
Solution 1:[1]
First import { useParams } from 'react-router-dom';
add const {id} = useParams();
And instead of using (match.params.id)
use only (id)
Hope this will work!
Solution 2:[2]
You can try to use hooks: useParams
, that returns an object with all variables inside your route
const params = useParams();
if the problem persists then it may be a problem with your component hierarchy or route definition
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Atul Yadav |
Solution 2 | vinzee |