yasinkuyuk
yasinkuyuk

Reputation: 101

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

Upvotes: 0

Views: 34

Answers (1)

A&#255;lo
A&#255;lo

Reputation: 311

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

Upvotes: 1

Related Questions