Home > Blockchain >  How to solve React Hook useEffect has missing dependencies error?
How to solve React Hook useEffect has missing dependencies error?

Time:10-03

How can I solve the Line 31:6: React Hook useEffect has missing dependencies: 'fetchUserName' and 'history'. Either include them or remove the dependency array react-hooks/exhaustive-deps ? I am not able to solve it. I am using Firebase for authentication. Please help me!!!!!

import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useHistory } from "react-router";
import "./Dashboard.css";
import { auth, db, logout } from "./firebase";

function Dashboard() {
  const [user, loading] = useAuthState(auth);
  const [name, setName] = useState("");
  const history = useHistory();

  const fetchUserName = async () => {
    try {
      const query = await db
        .collection("users")
        .where("uid", "==", user?.uid)
        .get();
      const data = await query.docs[0].data();
      setName(data.name);
    } catch (err) {
      console.error(err);
      alert("An error occured while fetching user data");
    }
  };

  useEffect(() => {
    if (loading) return;
    if (!user) return history.replace("/");

    fetchUserName();
  }, [user, loading]);

  return (
    <div className="dashboard">
      <div className="dashboard__container">
        Logged in as
        <div>{name}</div>
        <div>{user?.email}</div>
        <button className="dashboard__btn" onClick={logout}>
          Logout
        </button>
      </div>
    </div>
  );
}

export default Dashboard;

CodePudding user response:

Normally it should be fine to add 'fetchUserName' and 'history' to the array at the end of useEffect:

useEffect(() => {
  if (loading) return;
  if (!user) return history.replace("/");

  fetchUserName();
}, [
  user, 
  loading,
  fetchUserName,
  history
]);

CodePudding user response:

you could use this

useEffect(() => {
    if (loading) return;
    if (!user) return history.replace("/");

    fetchUserName();
    // eslint-disable-next-line
  }, [user, loading]);

CodePudding user response:

React functional component uses closures.
when state updates not all functions know the updated value, they only know the initialized value

when you are using useEffect you need to make sure that useEffect hook knows the updated values, even more, the functions that the useEffect invokes also need to know the updated values so if you have a warning that says you missing some dependencies, you probably need to listen to it

If you really don't need it and you want to remove the warning you can put this right before the end of the useEffect/ useCallback

        // eslint-disable-next-line react-hooks/exhaustive-deps

But again they didn't send this by mistake, there are reasons why they send it and a good ones

  • Related