Full stack mern app map returning undefined

I am trying to render posts by mapping over the posts array and then past individual post to Post component. However it prints the posts data on the console but doesnt render it on the screen.

import React from "react"
import Post from './Post/Post';
import { ThemeProvider } from "@mui/material/styles"
import theme from "./styles"
import { useSelector } from "react-redux"
import {Grid, CircularProgress} from '@mui/material'

const Posts = ({setCurrentId})=> {

    const posts = useSelector((state) => state.posts)
    console.log(posts);


    return (
        !posts.length ? <CircularProgress /> : (
          <Grid className={theme.mainContainer} container alignItems="stretch" spacing={3}>
            {posts.map((post) => (
              <Grid key={post._id} item xs={12} sm={6} md={6}>
                <Post post={post} setCurrentId={setCurrentId} />
              </Grid>
            ))}
          </Grid>
        )
      );
    };
    
    export default Posts;

I have tried optional chaining to check if the array exists. Bu i still get the same eror.

The error on screen says "Cannot read properties of undefined (reading ‘map’)
TypeError: Cannot read properties of undefined (reading ‘map’) ". On the console I get this error “Posts.js:15 Warning: Each child in a list should have a unique “key” prop.”

hello and welcome to fcc forum :slight_smile:

  • if you are seeing this on console, it should also render, also check at any point it also shows “undefind” in console as well
  • double check if data is “directly under it or not”, maybe data is within “posts.data” perhaps
  • meanwhile do you see loading screen here?!

hope this was useful, happy coding :slight_smile:

Do you have other maps in your code?

If posts is undefined, your length check should be throwing before the map. I also don’t think you would see the key warning.

If I console.log the data it first prints an empty array and then prints the data. I do see a loading screen there.
I fetch in my action creator via redux thunk and then pass the data to redux store. Then uss the useSelector hook to retrieve the data from the store.
I dont have any other map in the code. I did console.log(posts.length) it didn’t return undefined or throw error. It first printed 0 and then 1. Probably the component is rendering twice, I am not sure.