user12954623
user12954623

Reputation:

Why can't I map this array

Can you help me figure out why I am not able to map this array. Here below are the error and the codes I am running:

TypeError: posts.map is not a function

and here is my codes causing the above error:

import React from 'react';
import {useEffect, useState} from 'react';
import { Container, Row, Col } from 'bootstrap-4-react';

export default function Post() {
     //posts array to be mapped
    const [posts, setPosts] = useState([{ 
        title: "",
        postContent: ""
    }]);

    useEffect(() => {
    //fetches a GET route
        fetch(`${process.env.REACT_APP_SERVER_URL}/posts/:id`).then(res => {    
            if (res.ok) {
                return res.json()
            }
        }).then(jsonRes => setPosts(jsonRes));
    })

    return (
    <div>
        <h1>Hello</h1>
        //cant seem to be able to map this array
        {posts.map(post => {  
            <>
            <h1>{post.title}</h1>
            <p>{post.postContent}</p>
            </>
        })}
    </div>
    )}

Upvotes: 1

Views: 690

Answers (2)

Duoro
Duoro

Reputation: 308

This is maybe because the response is not an array. Try to console.log the response. You can also change its type by using Array.isArray(jsonRes). The second problem is you are not returning the individual element inside the map function.

{posts.map((post) => (
        <>
          <h1>{post.title}</h1>
          <p>{post.postContent}</p>
        </>
      ))}

Your useEffect also don't have any dependencies, this will result in fetching data on every render. So you must use an empty array as the second argument inside useEffect to tell it to execute only once.

    useEffect(() => {
    //fetches a GET route
        fetch(`${process.env.REACT_APP_SERVER_URL}/posts/:id`).then(res => {    
            if (res.ok) {
                return res.json()
            }
        }).then(jsonRes => setPosts(jsonRes));
    }, [])

Upvotes: 1

mallxowed
mallxowed

Reputation: 21

You need to wrap the mapped returned code block within parenthesis () and not in curly brackets {} in order to return the html correctly

//...


  return (
    <div>
      <h1>Hello</h1>
        {posts.map(post => (  
          <>
            <h1>{post.title}</h1>
            <p>{post.postContent}</p>
          </>
        ))}
    </div>
  )
}


Edit: Also, I suggest adding an empty dependency array as the second argument for your useEffect(() => { //your code }, []) This will make it so your component doesn't re-render sporadically and end up fetching your data a ridiculous amount of times.

Upvotes: 2

Related Questions