0
votes

Currently trying to make a MERN Stack web app from this tutorial : https://youtu.be/aibtHnbeuio So I'am pretty new too the stack and don't know how to fix this... help plz

TypeError: Cannot read property 'map' of undefined Post C:/Users/I/Desktop/memories-pr/client/src/components/Posts/Post/Post.js:27

  24 |     </Button>
  25 | </div>
  26 | <div className={classes.details}>
> 27 |     <Typography variant="body2" color="textSecondary" component="h2">{post.tags.map((tag) => `#${tag} `)}</Typography>
     |   28 | </div>
  29 | <CardContent>
  30 |     <Typography className={classes.title}  variant="h5" gutterBottom > {post.message} </Typography>

(anonymous function) C:/Users/I/Desktop/memories-pr/client/src/actions/posts.js:8

 5 | try {
   6 |     const { data } = await api.fetchPosts();
   7 | 
>  8 |     dispatch({ type: 'FETCH_ALL', payload: data});
     | ^   9 | } catch (error) {
  10 |     console.log(error.message);
  11 | }
1
I guess it means that post.tags is undefined? Have you tried printing the "post" variable to the console, or inspecting it in a debugger?sunero4
It is basically saying that, your post.tags is undefined. Try checking if fetched data properly or check if your post has a property - tags.adzo261
post.tags && post.tags.map((tag) => #${tag} - Add null checkSarun UK

1 Answers

1
votes

This might be caused by fetching post asynchronously, if that's the case then initially the value of post will remain undefined and you will be shown this error.

Use null propogation or conditional rendering to avoid this error:

<Typography 
    variant="body2" 
    color="textSecondary"    
   component="h2">
     {post?.tags?.map((tag) => `#${tag} `)}
</Typography>