saving and removing weekly schedule in async storage react native

Viewed 1005

I have a scenario in my project where i have to save weekly schedule with start and end time

What i want

user can enter day schedule with start and end time and can remove.

Also i have validation that if user has already a day schedule he can't save another on same day before removing first one.

What i've tried

AsyncStorage multiset and multiget

but i haven't reached at my goals.

Please lemme know how can i save and get back schedule from AsyncStorage either using objects or associative array.

UI pic

Help will be appreciated

3 Answers

You can only store Strings in AsyncStorage. You will need to stringify your Array/Object and parse back on retrieving.

Async Storage stores key and value pairs.

AsyncStorage.setItem(key, JSON.stringify(item));
AsyncStorage.getItem(key);
async setSchedule(schedule){
   try{
     let value = await AsyncStorage.getItem("schedule");
     if(value==null)
     {
        await AsyncStorage.setItem("schedule",JSON.stringify(schedule));
        console.log("schedule Not there);
     }
     else{
        console.log("schedule aldready set");
     }
   }
   catch(er){
   }
}

async removeSchedule()
{
   await AsyncStorage.removeItem("schedule")
}

async getSchedule()
{
   let value = await AsyncStorage.getItem("schedule")
   return JSON.parse(value)
}

Save the data as an object, and save it in async storage as a string using JSON.stringify

state = {
 schedule: [{ day: 'Monday', start: '9:00', end: '17:00'}]
}

save items as string

AsyncStorage.setItem('schedule', JSON.stringify(this.state.schedule));

Retrieve the items.

const items = await AsyncStorage.getItem('schedule');
const schedule = JSON.parse(items);

DEMO

Save the data as an object, and save it async storage as a string using JSON.stringify

state = {
 schedule: [{ day: 'Monday', start: '9:00', end: '17:00'}]
}

Save items as string

Related