0

I have a function that sends a request to the server to get posts. The response from the server is "200" , but when outputting this array it is empty. I use useEffect so that when I enter the page, it works immediately

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


function News() {
    let [post, setpost] = useState([])

    useEffect(()=>{
        getnews()
    }, [])
    
    async function getnews(){
        let responce =  await axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(responce=> setpost(responce.data))
        console.log(post)
    }

    return (<>
        <div className="main">
            <div className="main__name">
                <h1>New</h1>
            </div>
            <div className="main__post">

            </div>
        </div>
    </>);
}
export default News;

enter image description here

BrainCode
  • 3
  • 3
  • 1
    well `post` is still empty when you log it, because you're doing it before the request has finished. Even if you moved the console.log inside the `.then` though, it would still log as empty due to React state updates being async. But it will update on the following render, so if you actually make use of `post` in your rendered output this should work correctly. – Robin Zigmond Mar 26 '23 at 08:45
  • 1
    @RobinZigmond now I tried to bring them to the page through .map and lo and behold, it works. – BrainCode Mar 26 '23 at 08:48

0 Answers0