Muhammad Hassaan Ather
Muhammad Hassaan Ather

Reputation: 185

React Hook useEffect has missing dependencies: 'dispatch' and 'logout'. Either include them or remove the dependency array

i dont understand what is the problem with this code. Most of the times i am facing this issue and still not able to resolve.

const logout = () => {
    dispatch({ type: "LOGOUT" });
    dispatch({
      type: "EMPTY_CART",
    });
    history.push("/");
    setUser(null);
  };

  useEffect(() => {
    dispatch(getEachUserCart(user?.result?._id));

    const token = user?.token;
    setShowCartInfor(false);
    // JWT..
    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }
    setUser(JSON.parse(localStorage.getItem("profile")));
  }, [location, user?.result?._id, user?.token]);

Upvotes: 0

Views: 744

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281960

The warning is reported by your linter which says that you need to provide the dependency array according to the closure values you are using in the component.

To fix the warning you can update your code to add logout as a dependency to useEffect and use useCallback to declare logout function

const logout = useCallback(() => {
    dispatch({ type: "LOGOUT" });
    dispatch({
      type: "EMPTY_CART",
    });
    history.push("/");
    setUser(null);
  }, [history, dispatch, setUser]);

  useEffect(() => {
    dispatch(getEachUserCart(user?.result?._id));

    const token = user?.token;
    setShowCartInfor(false);
    // JWT..
    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }
    setUser(JSON.parse(localStorage.getItem("profile")));
  }, [location, user?.result?._id, user?.token, logout]);

You can fix the warning by moving the logout function within the useEffect too if it is not being called from elsewhere

useEffect(() => {
    
    const logout = () => {
        dispatch({ type: "LOGOUT" });
        dispatch({
          type: "EMPTY_CART",
        });
        history.push("/");
        setUser(null);
      };
    dispatch(getEachUserCart(user?.result?._id));

    const token = user?.token;
    setShowCartInfor(false);
    // JWT..
    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }
    setUser(JSON.parse(localStorage.getItem("profile")));
  }, [location, user?.result?._id, user?.token]); 

Upvotes: 3

Related Questions