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;