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:

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:
now if the logged in user is
user1, when you write:it is effectively
Boolean(likes["user1Id"]).Of course, this index does not exist, you only have three indices,
0,1and2.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: