Home > Mobile >  I get an arror for map function(posts.map is not a function)
I get an arror for map function(posts.map is not a function)

Time:04-26

I get this error, while I don't see any issue in that:

posts.map is not a function

import React from 'react'
import { useSelector } from 'react-redux'

export const PostsList = () => {
  const posts = useSelector(state => state.posts)

  const renderedPosts = posts.map(post => (
    <article className="post-excerpt" key={post.id}>
      <h3>{post.title}</h3>
      <p className="post-content">{post.content.substring(0, 100)}</p>
    </article>
  ))

  return (
    <section className="posts-list">
      <h2>Posts</h2>
      {renderedPosts}
    </section>
  )
}

This is my code Sandbox: https://codesandbox.io/s/wandering-darkness-6hi04d?file=/src/features/posts/PostsList.js

CodePudding user response:

Your problem in the file store.js

export default configureStore({
  reducer: () => ({
    posts: postsReducer
  })
});

Modify this file as follows :

export default configureStore({
  reducer: {
    posts: postsReducer
  }
});

CodePudding user response:

I think you want to make renderedPosts as a function, that way, you can map posts inside it.

const renderedPosts = () => {
    posts.map((post) => (
      <article className="post-excerpt" key={post.id}>
        <h3>{post.title}</h3>
        <p className="post-content">{post.content.substring(0, 100)}</p>
      </article>
    ));
  };
  • Related