How to get response value from somewhere other than axios function in React JS
P粉592085423
P粉592085423 2023-09-17 09:24:05
0
1
397

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粉592085423
P粉592085423

reply all (1)
P粉852578075

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;
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!