0

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

2
  • 2
    Is it possible there is a typo in your code? The error message would only make sense if the problematic line was const isLiked = Boolean(likes[loggedInUser.Id]); (notice the period). Commented Jan 20, 2023 at 19:27
  • +1 for what @TomášHübelbauer said, can you post the structure of the likes object? Is it also possible that Boolean(likes[loggedInUserId]) isn't populated/created when the function is run? Commented Jan 20, 2023 at 19:43

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Now i am getting a new error of "cannot read properties of undefined (reading: find)
Have you console logged likes to make sure there are values present when the component renders? If the values are not present on first mount, you will also get undefined. In which case, you can set isLiked as a state variable, and set it in a useEffect only when likes values are present.
Scott pls are you on discord so you can work me through via a call where i can share my screen with you. I would really appreciate it because i know I will learn something new

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.