Reputation: 9
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
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
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