For loop behaving when trying to clear all items asynchoronously when trying to remove all id's in an array of id's

Viewed 48

When trying to clear all items with a click of a button in React with a for loop, it is acting really weird in that visually it only removes one item. However, if I refresh the page, all items are indeed removed from the UI. Does anyone know why it is behaving in such a way? I am reusing an existing redux action that usually takes one parameter at a time. That is configId. Please see the code that I implemented that is behaving like this.

  const clearStoppedConfigs = async () => {
    for (let i = 0; i < filteredStoppedBots.length; i++) {
      for (const id in filteredStoppedBots) {
        await actions.deleteConfig(filteredStoppedBots[id]);
        ++i;
      }
    }
  };

BTW, the filteredStoppedBots above simply only contains array id's.

And here is the redux action

function deleteConfig(configId) {
  return {
    type: DELETE_CONFIG,
    configId
  };
}

And the delete api request

async function deleteConfig(configId) {
  const options = {
    method: 'DELETE',
    headers: {
      'content-type': 'application/json'
    },
    url: `${ALGOS_API_ROOT}/configs/${configId}`
  };
  return axios(options);
}

Any help is greatly appreciated. Thanks!

1 Answers

Seems multiple issues with clearStoppedConfigs, Not sure why you are iterating filteredStoppedBots twice, that too outer loop like array and inner loop like object. If it's just contains arrays of Id's then below code should work fine to remove multiple elements. Also incrementing i twice is not required too.

  const clearStoppedConfigs = async () => {
    for (let i = 0; i < filteredStoppedBots.length; i++) {
      await actions.deleteConfig(filteredStoppedBots[i]);
    }
  };
Related