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
CodePudding user response:
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>
)
};