-1

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;
A prasad
  • 143
  • 2
  • 16
  • I don't know what you were expecting here. Could be https://stackoverflow.com/q/54069253/3001761, or just a basic https://stackoverflow.com/q/14220321/3001761. – jonrsharpe Aug 11 '23 at 09:09
  • I just need the response value outside of function , but as per above code it is showing empty – A prasad Aug 11 '23 at 09:59

3 Answers3

1

I think you just have to console the value outside of useEffect like this:

import React, { useState, useEffect,useRef, useMemo  } from 'react';
import axios from 'axios';  
function App() {
    const [state, setState] = useState({});
    useEffect(() => {
        axios.get(`https://jsonplaceholder.typicode.com/todos/1`)  
      .then(res => {  
        // console.log(res.data)
        setState(res.data);  
      })  
    },[]);
    console.log(state)
}
export default App;
0

useState takes one render to change so if you read the state right after setState then you will always read previous value not updated value. For using the value instantly you should save the response in local variable.Like this

 useEffect(() => {
let response ="";
        axios.get(`https://jsonplaceholder.typicode.com/todos/1`)  
      .then(res => {  
response= res.data        
setState(res.data);  
      })  
      console.log(response)
    },
0

It won't change the state immediately, because they create queues to optimize performance. You can check the data being loaded in the div tags.

const Test = () => {
  const [state, setState] = useState();

  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/todos/1").then((result) => {
      setState(result.data);
    });
  }, []);

  if(state){
    return <div>{state.title}</div> 
  }

  return <div></div>;
};

export default Test;

For more information refer useState do not update immediately

Krish
  • 53
  • 1
  • 6