search

Home  >  Q&A  >  body text

How to get response value from somewhere other than axios function in React JS

I'm calling an API and getting the response correctly, but outside the response function the same response value is showing up as empty. I need to get it externally when the page loads. The following is the code:

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;
P粉592085423P粉592085423469 days ago538

reply all(1)I'll reply

  • P粉852578075

    P粉8525780752023-09-18 00:30:51

    I think you just need to console the value somewhere outside 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;

    reply
    0
  • Cancelreply