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:
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粉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;