Search code examples
javascriptnode.jsreact-nativeasyncstorage

How can I use Async Storage to save my data? - React Native


I'm new to using Async, let alone async storage. I have literally no idea what I'm doing my goal is to basically make use setWorkouts() to set workouts to the values I get from asyncstorage, and use this to save the workouts that are set.

Short Question: How can I save my data using Async Storage?

Code:

const submitHandler = async (text, reps, sets) => {
    if(text.length > 0 && reps.length > 0 && sets.length > 0){
      if(text.length <= 40){
        let newWorkout = {
          name: text,
          key: Math.random().toString(),
          reps: reps,
          sets: sets
        };
        writeData = async () => {
          try {
            await AsyncStorage.multiSet(['workouts', [
              newWorkout,
              ...workouts
            ]])
          } catch (err) {
            console.log(err)
          }
        }
        await Promise.all(AsyncStorage.getItem('workouts')).then((data) => {
          console.log(data[0])
        })
      }else {Alert.alert('Whoops!', "You entered over 40 characters! Shorten it up a bit!", [{text: 'Close '}])}
    }else {Alert.alert('Whoops!', "Make sure to enter something in each field!", [{text: 'Close '}])}
  }

Any help is useful!


Solution

  • To store data in async storage with any method we have to parse data in a string instead of passing objects in async storage functions we can convert objects to a string using JSON.stringify.

    so, we can try the below code example:

    const writeData = async (newWorkout) => {
       try {
           await AsyncStorage.multiSet(['workouts', JSON.stringify([
               newWorkout,
               ...workouts
           ]]))
       } catch (err) {
           console.log(err)
       }
    }
    
    const submitHandler = async (text, reps, sets) => {
        if(text.length > 0 && reps.length > 0 && sets.length > 0){
          if(text.length <= 40){
            let newWorkout = {
              name: text,
              key: Math.random().toString(),
              reps: reps,
              sets: sets
            };
            await writeData(newWorkout)
            await AsyncStorage.getItem('workouts').then((data) => {
                console.log(data)
            })
          } else {
              Alert.alert('Whoops!', "You entered over 40 characters! Shorten it up a bit!", [{text: 'Close '}])
          }
       } else {
           Alert.alert('Whoops!', "Make sure to enter something in each field!", [{text: 'Close '}])}
        } 
    }
    

    For more details related to set values using async storage and get values from async storage, check-out the official async storage docs.

    https://react-native-async-storage.github.io/async-storage/docs/api/