简体   繁体   中英

How to solve "useEffect has a missing dependency"?

I am creating a project where the data is been fetched from Firebase and the whole UI is working fine but a error is coming which is

Compiled with warnings.

src/Myproject.js
  Line 16:7:  React Hook useEffect has a missing dependency: 'fetchDB'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

but if we see the code

// Code...
const [allProjects,getAllProjects] = useState([
        {
            coverImg: null,
            dateOfpublish: "--/08/2021",
            demo: null,
            summary: "To showcase my skills",
            tag: "react",
            title: "Portfolio"
        }])
    const fetchDB =  async() =>{
        const getdata = db.collection('projects');
        const data = await getdata.get();
        data.docs.forEach(project=>{
            getAllProjects([...allProjects,project.data()])
        })
    }
    useEffect(()=>{
        fetchDB();
    },[])
// Code...

I can't find where it is going wrong...

this issue is closely related to this Issue but still, the solutions are given there are still not fixing my issue.

Whole code is there on Github

You are getting this error because fetchDB function will create every render and react is trying to warn you about if fetchDB was changed useEffect won't trigger after changes.

There are two ways to prevent this. First you can create the fetchDB function inside the useEffect like this.

    useEffect(()=>{
      const fetchDB =  async() =>{
        const getdata = db.collection('projects');
        const data = await getdata.get();
        console.log(data)
        data.docs.forEach(project=>{
            getAllProjects([...allProjects,project.data()])
      })
    }
      fetchDB();
    },[])

On the otherhand, You can use useCallback hook to prevent create fetchDB on every render with memoization

 const fetchDB =  useCallback(() => {
    async() =>{
        const getdata = db.collection('projects');
        const data = await getdata.get();
        console.log(data)
        data.docs.forEach(project=>{
            getAllProjects([...allProjects,project.data()])
        })
    }
}, [])

 useEffect(()=>{
    fetchDB();
 },[fetchDB])

I would try

const [allProjects,getAllProjects] = useState([])
    const fetchDB =  async() =>{
        const getdata = db.collection('projects');
        const data = await getdata.get();
        console.log(data)
        data.docs.forEach(project=>{
            getAllProjects([...allProjects,project.data()])
        })
    }
    useEffect(()=>{
        fetchDB();
    },[fetchDB()])

I would also rename

const [allProjects,getAllProjects] = useState([])

By

const [allProjects, setAllProjects] = useState([])
Or
const [projects, setProjects] = useState([])

And on your GitHub everyone can have access to your api keys and credentials. You should store sensitive informations in a.env or.env.local file and add this file to your gitignore.

This error has kept me up for days before I found a solve for it which is

 const fetchDB =  useCallback(async () => {
        const getdata = db.collection('projects');
        const data = await getdata.get();
        data.docs.forEach(project=>{
            getAllProjects([...allProjects,project.data()])
        })
}, [getAllProjects, allProjects])

 useEffect(()=>{
    fetchDB();
 },[fetchDB])

I have solved this by adding EventListener at the load

const [allProjects,getAllProjects] = useState([]);
    const fetchDB = () =>{
        db.collection("projects").get().then((querySnapshot) => {
            querySnapshot.forEach(element => {
                var data = element.data();
                getAllProjects(arr => [...arr,data]);
                console.log("is called")
            });
        });
    };
    useEffect(()=>{
        fetchDB()
    },[])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM