Home > Mobile >  Why does my array from backend doesn't print in the frontend ReactJS?
Why does my array from backend doesn't print in the frontend ReactJS?

Time:11-24

I have a simple 'Submit a post' project with 2 inputs (title and description) and a submit button.

Whenever I press submit, I send the title and description value to the backend where it it stored there in an array called submittedPosts. For example:

Code in the backend:

const submittedPosts = [ 
{
title: 'test',
description: 'test',
date: 'test'
   }
];

The problem is - I can't print ALL the array in the frontend to show the clients all the posts.

Things that I've tried but it did not work:

I've tried to get the array from the backend and assign it to the posts state, and then print it in the JSX as shown below:

Code in the frontend:

const loadAllPosts = async () => {
    const res = await axios.get("/api/posts");
    setPosts(res.data);
  };

//in JSX
<div>
    {posts}
</div>

I've also tried using map(), but I didn't do it correctly and got lost there...

I'd love to get a little help here.. Thanks.

CodePudding user response:

Since posts is an array you have to map every element of it to JSX elements so it can be rendered.

Let's say you want an h1 with the title, a paragraph with the description and a span with the date

<div>
    {posts.map((post)=>{
      return (
        <div key={post.id}>
          <h1>{post.title}</h1>
          <p>{post.description}</p>
          <span>{post.date}</span> 
        </div>
       )
     })}
</div>

You should also assign a key prop to every post, that's why I added key={post.id} despite your post structure not having it. You can assign the title as a key if you don't have unique id's for now but consider having unique id's

  • Related