Home > other >  React Hook useEffect has a missing dependency: 'match.params.id'
React Hook useEffect has a missing dependency: 'match.params.id'

Time:03-16

React Hook useEffect has a missing dependency: 'match.params.id'. Either includes it or remove the dependency array, this is the error I continuously get while using useEffect


  useEffect(() => {
    const fetchData = async () => {
      let data = await getPost(match.params.id);
      console.log(data);
      setPost(data);
    };
    fetchData();
  }, []);

CodePudding user response:

this will work, need to include 'match.params.id' in useEffect dependency array,

useEffect(() => {
    const fetchData = async () => {
      let data = await getPost(match.params.id);
      console.log(data);
      setPost(data);
    };
    fetchData();
  }, [match.params.id]);

CodePudding user response:

You need to update your dependency array in useEffect hook like below.

useEffect(() => {
    const fetchData = async () => {
      let data = await getPost(match.params.id);
      console.log(data);
      setPost(data);
    };
    fetchData();
  }, [match.params.id]);

According to the offical react documentation - the dependency array should includes all values from the component scope (such as props and state) that change over time and that are used by the effect.

You can check here for more info - Official doc link

  • Related