Home > database >  TypeError: Cannot read propertiy of undefined (reading 'includes')
TypeError: Cannot read propertiy of undefined (reading 'includes')

Time:05-11

I get

TypeError: Cannot read properties of undefined (reading 'includes'), 
Line of,  "const followed, setFollowed "

That's the real issue showing? but i don't understand what wrong in this??

  const PF = process.env.REACT_APP_PUBLIC_FOLDER;
  const [friends, setFriends] = useState([]);
  const { user: currentUser, dispatch } = useContext(AuthContext);
  const [followed, setFollowed] = useState(
    currentUser.followings.includes(user?.id)
  );

  
    getFriends();
  }, [user]);

  const handleClick = async () => {
    try {
      if (followed) {
        await axios.put(`/users/${user._id}/unfollow`, {
          userId: currentUser._id,
        });
        dispatch({ type: "UNFOLLOW", payload: user._id });
      } else {
        await axios.put(`/users/${user._id}/follow`, {
          userId: currentUser._id,
        });
        dispatch({ type: "FOLLOW", payload: user._id });
      }
      setFollowed(!followed);
    } catch (err) {}
  };```

CodePudding user response:

Variable currentUser doesn't have value the value 'followings' (thus is undefined)

Try giving it a default vale or using a short circuit syntax, or optional chaining operator

Short circuit syntax

currentUser.followings && currentUser.followings.includes(user?.id)

Optional chaining

currentUser.followings?.includes(user?.id)
  • Related