Nika Roffy
Nika Roffy

Reputation: 941

array.map is not a function reactJS

Whenever I'm trying to use my useDispatch() function from my reducer I'm getting error inside of my component again.

Here is my reducer with which I'm getting all Items from DB and displaying it on the page.

export const getPost = (posts : any ) => {


 return {
        type : actionTypes.GET_POSTS,
        posts
    }
}

Here is my useEffect in component :

    useEffect(() => {
    axios
        .get('http://localhost:4000/getPost')
        .then((res) => {
            // dispatch(actions.getPost({posts : res.data}))
            console.log('--------res', res.data);
        })
        .catch((err) => {
            console.log('--------err', err);

        })
})

Error is popping up on my map method here :

 <div id="posts">
            <ul>
                {posts.map((items : any) => {
                    return <li key={uuidv4()} onClick={() => history.push('/postsOnPage')}>{items.title}</li>
                })}
            </ul>
        </div>

The error itself is saying: posts.map is not a function And this is that posts : let posts : any = useSelector((state : any) => state.posts);

Any suggestions, please?

Upvotes: 0

Views: 366

Answers (2)

Muneeb
Muneeb

Reputation: 1549

It's probably because posts has non-array value (undefined, null etc.) while API hasn't fetched the data.

You can prevent the error by either checking the value of posts first and then running the map or setting the initial value of posts as an empty array.

<div id="posts">
        <ul>
         {/*Only run the map when posts exists and has the length > 0*/}
            {posts && posts.length > 0 && posts.map((items : any) => {
                return <li key={uuidv4()} onClick={() => history.push('/postsOnPage')}>{items.title}</li>
            })}
        </ul>
    </div>

Upvotes: 1

Neskews
Neskews

Reputation: 824

Try:

<div id="posts">
  <ul>
    {Array.isArray(posts) && posts.map((items : any) => {
      return (
        <li
          key={uuidv4()}
          onClick={() => history.push('/postsOnPage')}
         >
           {items.title}
         </li>
      )
     })}
  </ul>
</div>

Upvotes: 1

Related Questions