Undefined function in React

99 views Asked by At

I am having an error: Cannot read properties of undefined reading((Id)).

 const PostWidget = ({
    postId,
    postUserId,
    name,
    description,
    location,
    picturePath,
    userPicturePath,
    likes,
    comments,
  }) => {
    const [isComments, setIsComments] = useState(false);
    const dispatch = useDispatch();
    const token = useSelector((state) => state.token);
    const loggedInUserId = useSelector((state) => state.user._id);
    const isLiked = Boolean(likes[loggedInUserId]);
    const likeCount = Object.keys(likes).length;
  
    const { palette } = useTheme();
    const main = palette.neutral.main;
    const primary = palette.primary.main;
  
    const patchLike = async () => {
      const response = await fetch(`http://localhost:3001/posts/${postId}/like`, {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ userId: loggedInUserId }),
      });
      const updatedPost = await response.json();
      dispatch(setPost({ post: updatedPost }));
    };

The error is generated from const isLiked = Boolean(likes[loggedInUsrId]) which checks for a truthy value if an array of userId liked a post before it gets rendered on the home page.

I expected it to show my homepage and its corresponding output/logic but instead got this from my developer console:

enter image description here

1

There are 1 answers

3
Scott Mitchell On

the error is occurring because you are checking for a truthy value on an array of user ids, by using an index which also consists of the userId.

Imagine you have three likes as follows:

const likes = ["user1Id", "user2Id", "user3Id"];

now if the logged in user is user1, when you write:

const isLiked = Boolean(likes[loggedInUserId]);

it is effectively Boolean(likes["user1Id"]).

Of course, this index does not exist, you only have three indices, 0, 1 and 2.

What you could do is try to find the userId in the array, and if it exists then its truthy, if not, it's falsy, like:

const isLiked = likes.find((userId) => userId === loggedInUserId);