Mahid
Mahid

Reputation: 9

Uncaught TypeError: Cannot read properties of undefined (reading 'length')

I am developing a react app, but i am facing this error-> "Uncaught TypeError: Cannot read properties of undefined (reading 'length')". how to fix this? my code is:

import React from "react";
import { Grid, CircularProgress } from "@material-ui/core";
import Post from "./Post/Post";
import useStyles from "./styles";
import { useSelector } from "react-redux";

const Posts = () => {
  const posts = useSelector((state) => state.Posts);
  const classes = useStyles();

  console.log(posts);
  return (!posts.length ? <CircularProgress/> :(
   <Grid className={classes.container} container alignItems="stretch" spacing={3}>
      {
        posts.map((post)=> (
              <Grid key={post._id} item xs={12} sm={6}>
                <Post post = {post} />
              </Grid>
        ))
      }

   </Grid>
 )
  );
};

export default Posts;

Upvotes: 0

Views: 12673

Answers (4)

Aquarius
Aquarius

Reputation: 11

The error says the type of posts is Undefined. As you are getting that value from Posts in state object, that means that Posts is not initialized in your state. Try initializing "Posts" with empty Array([]) in your initial state object.

Upvotes: 1

Amir
Amir

Reputation: 52

try posts && <Grid>

Upvotes: 0

Harshad Naik
Harshad Naik

Reputation: 86

You can try something like this , !posts?.length > -1 ?. As you are checking if the post array is empty or not.

Upvotes: 0

Nick.Na
Nick.Na

Reputation: 11

use !post || !post.length or !posts?.length

Upvotes: 1

Related Questions