简体   繁体   中英

For Each Axios Call?

So the API for this software does not provide me all the data I need in 1 call. There is another endpoint that uses the data from the first endpoint to provide me with the data I actually need.

So what is happening, when the device first loads it is checking what store the device is used in. This is the first API call. Once that APi call is executed, I think query all the devices in the store with the API.

After that is where I am having a problem.

Once the I have the state of all the devices saved, It only contains partial information... for example when I query the devices in the store, the API only provides me with a serial number. However with a serial number I can query all the data I need, and I need that for all the devices.

So my question is, can React-Native do a foreach loop and save it into state?

I could not figure out state, I had to create an array.. but the problem is I have to refresh the screen for the state to save, which has been a problem.

I managed this, and while it does work, it does not save the array to state.

const array=[]

handleSetStoreDevices = () => {
    var axios = require('axios');
    storeInfo.forEach(async (item) => {
      var config = {
        method: 'get',
        url: URL,
        headers: {
          Accept: 'application/json',
          Authorization:
            'Basic ',
        },
      };

      await axios(config)
        .then(function (response) {
          console.log('next');
          array.push(response.data);
        })
        .catch(function (error) {
          console.log(error);
        });
    });
  };

I am looking to see if there is a way to do this and it manage the state?

You can go with Promise.all() . Here is the way I suggest. You can call this function inside a useEffect and save the return value to the state.

handleSetStoreDevices = async () => {
        var axios = require('axios');
        var config = {
            method: 'get',
            url: URL,
            headers: {
              Accept: 'application/json',
              Authorization:
                'Basic ',
            },
          };
        const response = await Promise.all(storeInfo.map(async (item) => {
          return axios(config)
            .then(function (response) {
              return response.data;
            })
            .catch(function (error) {
              console.log(error);
              return null;
            });
        }));

        return response;
      };

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