简体   繁体   中英

React.js Can I use array.map within componentDidMount() on an array returned from an axios request?

I'm making a foodtruck finder website and I'm running into an error. My team is separating foodtrucks and foodtruck schedules so we have to make 2 different axios calls to get all our data. Our issue is that we aren't getting our schedule from the backend but we are getting the foodtruck data. I'll provide the code:

 async componentDidMount(){
    // get the array of trucks
    let userData = await Request.findTrucksByOwnerID(this.state.ownerTruckID);

    this.setState({
        data: userData,
    });

    userData.map((truck) => {
    let scheduleData = await Request.getScheduleDTOByID(truck.id);
    this.setState({
        schedule: [...this.state.schedule, scheduleData]
    });


    });

    // get the array of schedules
    console.log(this.state.data);
  };

the functions called by Request

export async function findTrucksByOwnerID(id) {
  return await axios({
    method: "GET",
    url: constants.backend_url + "trucks/findTrucksByOwnerID",
    params: { id: id },
    headers: request_headers,
  })
    .then(function (response) {
      console.log(response.data);
      return response.data;
    })
    .catch(function (error) {
      console.log(error);
      return error;
    });
}

export function getScheduleDTOByID(id) {
  return axios({
    method: "GET",
    url: constants.backend_url + "schedule/getScheduleDTOByID",
    params: { id: id },
    headers: request_headers,
  })
    .then(function (response) {
      console.log(response.data);
      return response.data;
    })
    .catch(function (error) {
      console.log(error);
      return error;
    });
}

Can I do Axios requests inside a map function the way I'm doing currently? I'm very new to using React so any info would be appreciated!

Responding to your comment. This is my suggested solution:

async componentDidMount() {
  // get the array of trucks
  let userData = await Request.findTrucksByOwnerID(this.state.ownerTruckID);

  const requests = userData.map(truck => Request.getScheduleDTOByID(truck.id));

  const listOfScheduleData = await Promise.all(requests);

  this.setState({
    // depends on if you want to keep original `this.state.schedule`

    // if you do:
    schedule: [...this.state.schedule, ...listOfScheduleData]

    // if you don't:
    schedule: listOfScheduleData
  });
}

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