Home > database >  React Fetch Inside a function Map
React Fetch Inside a function Map

Time:12-31

I'm trying to make a request for each item captured in the MAP, but I would like to wait for the response before going to the other object within the MAP. At the moment my code is making all the requests at the same time, which ends up crashing the Backend.

    function RequestComputers (Computers) {
        Computers.map((e) => {
            Details(e, data.region, data.apitoken).then(data => {  
                if(data)
                setContent2((array) => [...array, data[0]])} ).catch(error => console.log(error))
            
    
        })
    
}
const Details = async (Computer, region, token) => {
    try {
        const test = {'region': region, 'apitoken': token, 'product': '1', 'computer': Computer}
        const response = await fetch('url', {
        method: 'POST',
        headers: {
           'Content-Type': 'application/json'
           },
           body: JSON.stringify(test)
        }
        )
        const data = await response.json()
        return data
       } catch(error) {
          console.log(error)
         } 
    }

I need to wait for the fetch response and only then make another fetch request

CodePudding user response:

You can use a simple for loop:

async function RequestComputers (Computers) {

    for ( const computer of Computers ) {

      try {
        const data = await Details(computer, data.region, data.apitoken);
        if ( data ) {
            setContent2((array) => [...array, data[0]]);
        }
      } catch(error){
          console.log(error);
      }

    }

}

Reference

CodePudding user response:

I think you could use .forEach and await Details:

async function RequestComputers (Computers) {
    
    Computer.forEach((computer) => {
      try {
        const data = await Details(computer, data.region, data.apitoken);
        if ( data ) {
            setContent2((array) => [...array, data[0]]);
        }
      } catch(error){
          console.log(error);
      }
    })
}

  • Related