Search code examples
react-nativeasyncstorage

How to Add items to React Native AsyncStorage


I'm building an application where user inserts a task and the time at which the task was created and both are saved into asyncStorage in react native. When a new task is added to the asyncstorage,i expected both the previous task and the new task to be displayed by the getItems() function. How can it be done?

async function saveItems() {
      const items = []
              items.push(task,timestamp )
              await AsyncStorage.setItem('key', JSON.stringify(items))
          }

     async function getItems() {
          try {
            const items =  await AsyncStorage.getItem('key');
            if (items !== null) {
              console.log(JSON.parse(items));
            }      
          } catch (error) {
            console.log(error)
          }
         }

Solution

  • async function saveItems() { 
       var items = AsyncStorage.getItem('key');
       if(items)
           items.push([task,timestamp] ) 
      await AsyncStorage.setItem('key', items);
     } 
    
    async function getItems() { 
             const items = await AsyncStorage.getItem('key');
             if (items !== null)
             console.log(items);
    }
    

    Items will be array of arrays Ex :

    items = [[task1,timestamp1],[task2,timestamp2]]