0

I'm using react native, I'm coding in javascript, and I'm using actual hardware and not an emulator.

I am trying to set tempGroups with data from AsyncStorage and then set my Group state that value. However, it is setting Group the empty array then filling the array with the data. How do I fix this?

const LoadData = async () => {
    let tempGroups = [];
    console.log("start: " + tempGroups.length);
    try {
      var keys = await AsyncStorage.getAllKeys();
      keys.forEach(async (element) => {
        var data = JSON.parse(await AsyncStorage.getItem(element));
        tempGroups.push({ key: element, name: data.name, tasks: data.tasks });
        console.log("inside: " + tempGroups.length);
      });
    } catch (e) {
      alert("There was an issue loading local data :c");
    }
    console.log("outside: " + tempGroups.length);
    SetGroups(tempGroups);
  };

This is the output from the console.log:

start: 0
outside: 0
inside: 1
inside: 2

Things I've already tried:

- Changing let to var, it doesn't fix it.
- Adding an await to the push, I get a warning saying it won't do anything.
- Directly setting the Group 'SetGroup([{ key: element, name: data.name, tasks: data.tasks },...Group]);', this causes duplicate data to appear
Marnie Rodriguez
  • 431
  • 2
  • 8
  • 22

1 Answers1

1

You can't use async with forEach. It won't wait for the promise to resolve. You need to use map and Promise.all:

tempGroups = await Promise.all(keys.map(async (element) => {
  const data = JSON.parse(await AsyncStorage.getItem(element));
  return { key: element, name: data.name, tasks: data.tasks };
}));
Andrew Dibble
  • 782
  • 6
  • 15