Reputation: 31
I am making a social media website from a youtuber and I am having a issue in frontend (React) part. My error is : Cannot read properties of null (reading '_id') I have checked many times by commenting every part and the issue is in Post .Please Help
const Account = () => {
const dispatch = useDispatch();
const { loading, error, posts } = useSelector((state) => state.myPosts);
const { error: likeError, message } = useSelector((state) => state.like);
useEffect(() => {
dispatch(getMyPosts());
}, [dispatch]);
useEffect(() => {
if (error) {
alert.error(error);
dispatch({ type: "clearErrors" });
}
if (likeError) {
alert.error(likeError);
dispatch({ type: "clearErrors" });
}
if (message) {
alert.success(message);
dispatch({ type: "clearMessage" });
}
}, [alert, error, message, likeError, dispatch]);
return loading ? (
<Loader />
) : (
<div className="account">
<div className="accountleft">
{posts && posts.length > 0 ?
posts.map((post) => (
<Post
key={post._id}
postId={post._id}
caption={post.caption}
postImage={post.image.url}
likes={post.likes}
comments={post.comments}
ownerImage={post.owner.avatar.url}
ownerName={post.owner.name}
ownerId={post.owner._id}
isAccount={true}
isDelete={true}
/>
))
: (
<Typography variant="h6">You have not made any post</Typography>
)}
</div>
<div className="accountright"></div>
</div>
);
};
export default Account;
Upvotes: 1
Views: 6472
Reputation: 26
This appears to be an issue with the post object you are currently looping over being null. You need to do a check for the value being null inside your loop.
{
posts && posts.length > 0 ? (
posts.map((post) =>
post ? (
<Post
key={post._id}
postId={post._id}
caption={post.caption}
postImage={post.image.url}
likes={post.likes}
comments={post.comments}
ownerImage={post.owner.avatar.url}
ownerName={post.owner.name}
ownerId={post.owner._id}
isAccount={true}
isDelete={true}
/>
) : null
)
) : (
<Typography variant="h6">You have not made any post</Typography>
);
}
edit: Unlike what others appear to be saying, this is neither an issue with the _id
property or the posts loop as this wouldn't create the same error. It is attempting to read the _id
property of post
and is finding post
to be null, not the property _id
.
Upvotes: 1