I'm trying to store an array of email addresses in my Async Storage. Think of it as "recently used accounts" to speed up login on a device that gets used by multiple users
Here's what I've got so far- this gets called after a user successfully logs in:
const storeEmail = async (email) => {
try {
const jsonValue = JSON.stringify(email);
await AsyncStorage.setItem("storedEmails", jsonValue);
} catch (e) {
alert(e);
}
};
My problem is that it only ever stores one email. How do I store an array of emails in there, rather than a single email?
I'd also need to avoid duplicates, so would need to check if an email address already exists in the array?
You can push the array data like shown below. Initially you can fetch data, if its empty than you can initialise empty array and push data into it. If it has data than you may append the email ID uniquely:
const storeEmail = async (email) => {
try {
let emailStored = await AsyncStorage.getItem("storedEmails");
if(emailStored == null || emailStored == undefined){
emailStored = [];
emailStored = JSON.stringify(emailStored)
}
let emails = JSON.parse(emailStored);
if (emails.indexOf(email) == -1) {
emails.push(email);
}
const jsonValue = JSON.stringify(emails);
await AsyncStorage.setItem("storedEmails", jsonValue);
} catch (e) {
alert(e);
}
};