skip to Main Content

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


  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;
    
    Login or Signup to reply.
  2. 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)
        },
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search