Home > Software design >  in react i can't use map funcation
in react i can't use map funcation

Time:10-10

when I run this code I got an error, the error "Uncaught TypeError: Cannot read properties of undefined (reading 'map')." I don't understand how I solve this problem.

import React from 'react';
import { useSelector } from 'react-redux';
import { selectAllPosts } from './PostSlice';

const PostList = () => {
const Posts = useSelector(selectAllPosts);
const renderedPosts = Posts.map(post =>(
    <article
    key={post.id}>
     <h3>{post.title}</h3>
     <p>{post.content.substring(0,100)}</p>
    </article>
))
    return (
        <div>
            <h2>Posts</h2>
            {renderedPosts}
        </div>
    );
};

export default PostList;

CodePudding user response:

I assume Posts are array. So that you can check if Posts array has length or not to render in map function.

const renderedPosts = Posts?.length > 0 && Posts.map(post =>(
    <article
    key={post.id}>
     <h3>{post.title}</h3>
     <p>{post.content.substring(0,100)}</p>
    </article>
))

CodePudding user response:

Add empty array check before mapping:

Posts && Posts.map(post =>{});

or,

if(Posts.length>0)Posts.map(post =>{});

or,

if(Posts!==[])Posts.map(post =>{});
  • Related