Unable to push to array using a loop.
MarkBlythe opened this issue · comments
I have an array of purchased item keys that I store using this module. Saving one at a time (when the purchase is made) works perfectly with store.push
however I now need to be able to store more than one value at a time in the array.
To do this I assumed it would be possible to use a for loop and just call store.push
inside.
However this is not the case and it only seems to store the final iteration ignoring any previous calls to the store method.
for (i = 0; i < purchases.length; i++) {
store.push('devicePurchasedKeys', key)
}
Could you please advise if there is a method that will achieve this as if there is I can't see it mentioned.
Try this
let data = [];
for (i = 0; i < purchases.length; i++) {
data.push(key);
}
store.push('devicePurchasedKeys', data)
I would do something similar to what @nursanamar suggests, with a change to .get
the original array if it exists and then call .save
to update it instead of .push
since pushing would add an array as the value of a single index in the devicePurchasedKeys
array. This would probably be the simplest way to do it.
updatePurchasedKeys = async (purchases) => {
const purchasedKeys = await store.get('devicePurchasedKeys') || [];
purchases.forEach((purchase) => {
purchasedKeys.push(purchase);
});
await store.save('devicePurchasedKeys', purchasedKeys);
}
If you were looking for another way around this you could implement an async forEach yourself, but I think this way gets the job done.
Thanks guys, I had to use the async function @jasonmerino suggested and it worked in the end.