sorry for the trivial question (maybe) but I've been hitting my head for hours. where is the mistake?
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { SingleCoin } from '../config/api';
const {id} = useParams();
const [coins, setCoins] = useState();
const {currency, symbol} = CryptoState();
useEffect(()=>{
const fetchCoins = async () => {
const {data} = await axios.get(SingleCoin(id));
setCoins(data);
};
fetchCoins();
}, []);
React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency array
CodePudding user response:
Any variable that you use in the useEffect
function needs to be in the dependency array, so that it is can be monitored and the useEffect will only be run when that variable changes.
useEffect(()=>{
const fetchCoins = async () => {
const {data} = await axios.get(SingleCoin(id));
setCoins(data);
};
fetchCoins();
}, [id]);
Add id
to the array that is the second parameter of useEffect
to clear this error.
Reference
CodePudding user response:
useEffect and some other hooks need a dependency array provided. It's the last argument passed as an array. The dependencies tell the hooks which variables or elements to observe for changes. If a dependency changes, the hook should also expect a new behavior and will therefor update.
To fix your issue, you need to provide the id in your dependency array as the warning states like so: React Hook useEffect has a missing dependency: 'id'
useEffect(()=>{
const fetchCoins = async () => {
const {data} = await axios.get(SingleCoin(id));
setCoins(data);
};
fetchCoins();
}, [id]);