Search code examples
javascriptreactjsreduxreact-redux

WARNING in [eslint] React Hook UseEffect has a missing dependency


This is the code

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import Header from './../components/Header';

const SingleProduct = ({ match }) => {
  const [product, setProduct] = useState({});

  useEffect(() => {
    const fetchproduct = async () => {
      const { data } = await axios.get(`/api/products/${match.params.id}`);
      setProduct(data);
    };
    fetchproduct();
  }, []);

and I keep getting this warning

WARNING in [eslint]
src\screens\SingleProduct.js
  Line 14:6:  React Hook useEffect has a missing dependency: 'match.params.id'. Either include it or 
remove the dependency array  react-hooks/exhaustive-deps

I'm a beginner so I don't really know how to fix it


Solution

  • your effect depends on the match.params.id, which was not present in the dependency array, adding it will solve the issue.

     useEffect(() => {
        const fetchproduct = async () => {
          const { data } = await axios.get(`/api/products/${match.params.id}`);
          setProduct(data);
        };
        fetchproduct();
      }, [match.params.id]); // ADD HERE