I am calling an API and getting the response properly but same response value is showing empty outside the response function. I need to get it from outside while page onload.Code below
Test.js
import React, { useState, useEffect,useRef, useMemo } from 'react';
import axios from 'axios';
function Test() {
const [state, setState] = useState([]);
useEffect(() => {
axios.get(`https://jsonplaceholder.typicode.com/todos/1`)
.then(res => {
setState(res.data);
})
console.log(state)
},
[]);
}
export default Test;
3
Answers
I think you just have to console the value outside of useEffect like this:
useState
takes one render to change so if you read thestate
right aftersetState
then you will always read previous value not updated value.For using the value instantly you should save the
response
in local variable.Like thisIt won’t change the state immediately, because they create queues to optimize performance. You can check the data being loaded in the div tags.
For more information refer useState do not update immediately