Search code examples
javascriptreactjsaxiosfetch

React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency array


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


Solution

  • 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