Home > database >  How to fix missing dependency warning when using useEffect and useParams React Hook
How to fix missing dependency warning when using useEffect and useParams React Hook

Time:08-11

import React from 'react'
import { useParams, useEffect, useState } from 'react'
import axios from "axios";
import './App.css';
const Todo = () => {
  const [todoDetails, setTodoDetails] = useState();
  const { id } = useParams();
  useEffect(() => {
// I wanted to fetch the data for the specific id from the jsonPlaceholder url to practice 

    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .then((res) => {
        const responseTodo = res.data;
        setTodoDetails(responseTodo);
      });

  }, [])//the console said the error is here but i don't know what to do 
// the error is "  Line 17:6:  React Hook useEffect has a missing dependency: 'id'. Either include it or remove the dependency array  react-hooks/exhaustive-deps"
  const { id: todoId, userId, title, completed } = todoDetails || {}
  return (
    <div>{`this is the todoes componets and the id is  ${todoId} , ${userId}, ${title}, ${completed}`}</div>
  )
}
export default Todo;

**I'm very new in the developer world i just started learning JS. I was asked to do a project using react js any tips would really help me out **

CodePudding user response:

The useEffect uses a dependency array as the second argument to watch changes, so basically if you leave the dependency array empty the useEffect will only run once when the component mounts.

If you add a property or more in the dependency array it will run everytime those values change.

In this case your useEffect is using the id to make the api call but I'll only run once, the warning is telling you that, so if the id prop changes the useEffect won't run

Add this if you want the useEffect to be run everytime the id changes:

useEffect(() => {
  // Rest of the code.  
  // Adding the id here will make this effect to run everytime the id changes.
  }, [id])

CodePudding user response:

It's about COMPONENTDIDUPDATE in react hooks, you can learn more about state and lifecicle concept in https://reactjs.org/docs/state-and-lifecycle.html. Your code must be like this:

useEffect(() => {
    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${id}`)
      .then((res) => {
        const responseTodo = res.data;
        setTodoDetails(responseTodo);
      });

  }, [id])
  • Related