Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Cannot setting the state with the data fetched in useEffect -React

I want to send an API request in useEffect hook and setting the state variables value with the fetched data. I added 2 console.log for detecting the state variables value. I except the second log to be setted with the fetched data, however it still prints null.

Here is my code:

import { useEffect, useState } from "react";
import axios from "axios";
const Test = () =>{
    const [users, setUsers] = useState(null);
    useEffect(()=>{
        const getData = async ()=>{
            const resp = await axios.get("https://jsonplaceholder.typicode.com/todos");
            console.log(users);
            setUsers(resp.data);
            console.log(users);
        };
        getData();
    },[])
    return (
        <div>hello</div>
    )
};

export default Test;

Additionally the console output look likes this:

null
null
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

useState's setter is asynchronous, therefore your second console.log will be called before the users is actually updated.

For it to work, just put it outside the useEffect.

import { useEffect, useState } from "react";
import axios from "axios";
const Test = () =>{
    const [users, setUsers] = useState(null);
    useEffect(()=>{
        const getData = async ()=>{
            const resp = await axios.get("https://jsonplaceholder.typicode.com/todos");
            console.log(users);
            setUsers(resp.data);
        };
        getData();
    },[])
    console.log(users);
    return (
        <div>hello</div>
    )
};

export default Test;

or in another dedicated useEffect, by passing users in the dependencies array.

import { useEffect, useState } from "react";
import axios from "axios";
const Test = () =>{
    const [users, setUsers] = useState(null);
    useEffect(()=>{
        const getData = async ()=>{
            const resp = await axios.get("https://jsonplaceholder.typicode.com/todos");
            console.log(users);
            setUsers(resp.data);
        };
        getData();
    },[])

    useEffect(()=>{
       console.log(users);
    },[users])

    return (
        <div>hello</div>
    )
};

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!