Search code examples
javascriptreactjsreact-hooksdependencies

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


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 **


Solution

  • 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])