because you're using something that is defined outside of useEffect
(in this case fetchProduct
function), react will throw a warning saying if something changes inside the fetchProduct
function, useEffect
will not catch that change. for example: let's say your match.params.id
inside fetchProduct
is equal to 1
when the page first loaded, but later on match.params.id
becomes 2
, the fetchProduct
function inside useEffect
will still use 1
as match.params.id
because useEffect
didn't catch the changes.
so to solve the warning, there are 2 options. first is to write the fetchProduct
function logic inside useEffect
:
useEffect(() => {
axios
.get(`https://fakestoreapi.com/products/?id=${match.params.id}`)
.then((res) => {
setData(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
}, [match.params.id]);
having match.params.id
in dependency array to make sure useEffect
is up to date.
but if you need to reuse the fetchProduct
function, then you should do something like:
const fetchProduct = useCallback(() => {
axios
.get(`https://fakestoreapi.com/products/?id=${match.params.id}`) // use match to get product id
.then((res) => {
setData(res.data);
console.log(res.data);
})
.catch((err) => console.log(err));
}, [match.params.id]);
useEffect(() => {
fetchProduct();
}, [fetchProduct]);