Newby
Newby

Reputation: 13

react hook useffect has a missing dependency

How did it fix it? I want it not to notify when run in command. It looks awkward

useEffect(() => {
   loadWishlist();
}, []);
    
const loadWishlist = () =>
   getWishlist(user.token).then((res) => {
   // console.log(res);
   setWishlist(res.data.wishlist);
});

Upvotes: 1

Views: 240

Answers (2)

Dhaval L.
Dhaval L.

Reputation: 657

There are multiple ways. One of them is to move your function inside useEffect and pass the dependency i.e. [user.token, setWishlist, getWishlist].

Refer here for more: How to fix missing dependency warning when using useEffect React Hook?

Upvotes: 0

HMR
HMR

Reputation: 39290

You could try the following:

//I assume setWishlist is local state
const [wishList, setWishlist] = useState();
//assuming you want to use loadWishlist outside the effect
const loadWishlist = useCallback(
  () =>
    //assuming getWishlist is defined outside of the component
    getWishlist(user.token).then((res) => {
      // console.log(res);
      setWishlist(res.data.wishlist);
    }),
  [user.token]//loasWishlist is re created when user.token changes
);
useEffect(() => {
  loadWishlist();
}, [loadWishlist]);//effect will run every time user.token changes

Upvotes: 1

Related Questions