Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map Function isnt working with proper array in React

I’m trying to pass in an array through a the component "Feed" and having it destructured and mapped accordingly. The issue is that when I pass an array through, I get an error saying

"Feed.js:5 Uncaught TypeError: allPosts.map is not a function"

I know for a fact I’m passing through an array because I tested my allPosts variable through console.log, and I know that my feed component is fine because if passed a concrete array, it works. Can anyone find and explain the issue to me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Feed/js

import React from "react";

const Feed = ({ allPosts }) => {
  return (
    <>
      {allPosts.map((posts) => {
        const { author, title, body } = posts;
        return (
          <div className="post">
            <h1>{author}</h1>
            <h1>{title}</h1>
            <h1>{body}</h1>
          </div>
        );
      })}
    </>
  );
};

export default Feed;

Dashboard.js

import React, { useEffect, useState } from 'react'
import { useAppContext } from '../context/AppContext.js'
import styled, {createGlobalStyle} from 'styled-components'
import TextField from "@mui/material/TextField";
import axios from 'axios';
import { GlobalStyles } from '@mui/styled-engine'
import mongoose from 'mongoose'
import Feed from '../components/Feed.js';
const GlobalStyle = createGlobalStyle`
body{
    background-color: white;
    display: flex;
    justify-content: center;
}
`
const Wrapper = styled.div`
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
h1{
    text-align: center;
    font-size: 3rem;
    margin-top: 2rem;
}
.feedTitle{
    text-align: center;
    margin-top: 4rem;
    font-size: 2rem;
    font-weight: 400;
}
.newPostForm{
    max-height: auto;
    width: 40rem;
    box-shadow: 0px 0px 20px 5px rgba(0,0,0,0.1);
    border-radius: 2rem;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
}
.title{
    width: 10rem;
    margin-left: 2rem;
    margin-bottom: 1rem;
    margin-top: 2rem;
}
.body{
    width: 36rem;
    height: auto;
    margin: 1rem 0 2rem 2rem;
}
.submitBtn{
    width: 5rem;
    height: 3rem;
    margin-right: 2rem;
    align-self: flex-end;
    background-color: lightblue;
    border-radius: 2rem;
    border: none;
}
.feedMain{
    height: 30rem;
    width: 40rem;
    box-shadow: 0px 0px 20px 5px rgba(0,0,0,0.1);
    border-radius: 2rem;
    margin-top: 4rem;
}
`

const Dashboard = () => {
    const {user, postNewPost} = useAppContext()
    const [allPosts, setAllPosts] = useState({})
    const getAllPosts = async() =>{
        const allPostsObject = await axios.get('api/v1/feed/getAllPosts')
        setAllPosts(allPostsObject.data)
    }
    useEffect(()=>{
        getAllPosts()
    }, [])
    
    const intialPostState = {
        userId: user.id,
        author: user.name,
        title: '',
        body: '',
    }
    const [post, setPost] = useState(intialPostState)
    const handleSubmit = (e)=>{
        e.preventDefault()
        postNewPost(post)
    }
    const handleChange = (e) => {
        setPost({ ...post, [e.target.name]: e.target.value });
        
      };
  return (
    <>
    <GlobalStyle/>
    <Wrapper>
        <h1>Welcome Back {user.name}</h1>
        <h1 className="feedTitle">Your Daily Feed</h1>
        <div className="newPostForm" onSubmit={handleSubmit}>
        <TextField
            placeholder="Title"
            type="title"
            className="title"
            name="title"
            variant="standard"
            size="medium"
            value={post.title}
            onChange={handleChange}
          />
          <TextField
            placeholder="Body"
            type="body"
            className="body"
            name="body"
            variant="outlined"
            size="medium"
            multiline
            value={post.body}
            onChange={handleChange}
          />
          <button type="submit" className="submitBtn" onClick={handleSubmit}>Post</button>
          </div>
          <Feed allPosts={allPosts}/>
    </Wrapper>
    </>
  )
}

export default Dashboard

allPosts value after useEffect

[
{
author: "hetpatel"
body: "Testing my first blog post"
title: "Testing"
userId: "62dc23faf8b5fbf1f30a478d"
__v: 0
_id: "62e951d390abbe8e5b308aa7"
}
]

>Solution :

you get an error because you can’t use map method on an empty object, which is the initial value of this state. replace it with an empty array and it should work just fine.

const [allPosts, setAllPosts] = useState([])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading