0

I was working on a MERN app. In a component i need to request a api. I used axios and used it in useEffect & then i used setState to set state to the response i get from api. But the state is not updating. I saw some youtube tutorials but they are doing the same code & getting the state updated. Is this because of new version of react @17.0.1 which i am using.

At last how do i solve this problem.....? need help.

posts.js file inside react app-

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const Posts = () => {
  const [posts, setPosts] = useState([]);

  useEffect(async () => {
    const res = await axios.get('http://localhost:5000/posts');
    console.log(res.data); // res.data is a array of objects
    setPosts(res.data);  // this is not working...

  }, []);

  return (
    <div>
      {posts.forEach((post) => {
        <ul>
          <li>{post.username}</li>
          <li>{post.content}</li>
        </ul>;
      })}
    </div>
  );
};

export default Posts;
  • 1
    The problem is not the setState the problem is that you are trying to render the posts with a forEach. You have to use a map to actually create an array of jsx elements. – giggo1604 Feb 01 '21 at 11:41
  • Try first time to console.log the state inside render and told us if you receive data ( delete foreach ) – Florin Feb 01 '21 at 11:45

1 Answers1

2

I hope you understand the basic principle of using map method here,

Generally speaking (for each) doesn't return anything. Meaning that Data from looping the original array won't reusable after the loop

But map method return another array

You can read here Map vs foreach

So what you doing now is

{posts.forEach((post) => {
        <ul>
          <li>{post.username}</li>
          <li>{post.content}</li>
        </ul>;
      })}

This syntax is actually looping the undefined . Which will return nothing.

if you wanna loop you need to use map method

{posts.map((post) => {
        return  <div>.....</div>;
  })}
Khant
  • 958
  • 5
  • 20