简体   繁体   中英

How to extract data from axios GET request object in React?

Currently I've been pulling data from an API using axios and the useEffect Hook in React. This is done by having the user enter a value into the code field which will be used to make a request to the API. However, when it comes to extracting the data and getting it to display on the page I've been having issues. Normally, I would use data.map() to map the array data to different fields, but when pulling from this API I am getting a project object which I've been having issues mapping to fields for displaying on the application. In addition, I've also noticed that the useEffect hook is constantly being called over and over in the console, and I dunno how to make it be called only once as well. If anyone could help with either of these issues that would be greatly appreciated!

home.js

import React, { useState, useEffect } from 'react';
import axios from "axios";
import './Home.css';                        // Import styling

function Home() {

    const [data, setData] = useState([])
    const [state, setState] = useState({
        code: ""
      })

    const handleChange = e => setState(prevState => ({ ...prevState, [e.target.name]: e.target.value }))

 
    useEffect(() => {
        axios.get(baseURL)
            .then((response) => {
                setData(response.data);
                console.log(data)
            });
    });

    
    return (
        <div className="form-container">
            <h1>axios-test</h1>
            <div className="form-group">
                    <label>Code</label>
                    <input type="text" className="form-control" name="code" value={state.code} onChange={handleChange}/>
            </div>
            <div className="form-group">
                    <label>Lead</label>
                    <input type="text" className="form-control" name="Lead" value={data.map(data => data.project.primaryLeaderName)} onChange={handleChange} disabled/>
            </div>
        </div>
    )

}

export default Home;

console output

There are two issues with your useEffect call.

  1. You are missing the dependency array. Check out the documentation . You should add [] as the second argument to useEffect if you only want this to run the first time the component mounts.
  2. console.log(data) . You are expecting data to have the new value, but this is not guaranteed by React. The call to setData updates data , but you won't be able to access the new value inside of the same useEffect call. In this case, I don't think you need to though. It's worth pointing out as that's a common gotcha with learning useEffect

Finally, there's a slight issue in this section, based on the screenshot of the data:

value={data.map(data => data.project.primaryLeaderName)} 

Check out the documentation on Array.prototype.map . data does not have a project key. In fact, you're mapping projects. The best naming convention is to name the element in the function after what it represents. Each element in data is a project. So:

value={data.map(project => project.primaryLeaderName)} 

I would suggest adding the dependency array [] in the useEffect and also use useEffect hook to call a function =>

const fetchData = async ()=>{
    const {data} = await axios.get('url')

// we await the response and destruct it to get only the data setState(data) }

 useEffect(()=>{
 fetchData()
     },[])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM