简体   繁体   中英

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

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>
    )
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM