Home > Software engineering >  Map Function isnt working with proper array in React
Map Function isnt working with proper array in React

Time:08-03

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.

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"
}
]

CodePudding user response:

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([])
  • Related