Search code examples
javascriptreact-nativevue.jsvue-native

AsyncStorage not storing data


I have looked at the documentation on asyncStorage through but don't understand why it is not saving my data. I am using Laravel for API and Vue native(a wrapper around react-native). When a user signs up I pass the token generated this way

import AsyncStorage from '@react-native-async-storage/async-storage';
...
handleRegister() {
  axios.post('/api/mobile-register', this.formData).then(response => {
    console.log(response.data);
    var token = response.data


    async(token) => {
      try {
        await AsyncStorage.setItem('@user_Token', token)
      } catch (e) {
        // save error
      }

      console.log('Done.')
    }
    console.log('User Registered!');

  }).catch(error => console.log(error));
},

The token is returned and logged as a string and the user is registered but the token is not saved. I tried to check the saved token using this in the mounted hook and attached to a button but it returns null

 astore(){
    AsyncStorage.getItem('@user_Token').then((res) => console.log(res))

  },

How can I do this correctly?


Solution

  • It would make more sense to remove the anonymous function that does not exist and simply make the callback the async function:

    axios.post('/api/mobile-register', this.formData).then( async response => {
      console.log(response.data);
      var token = response.data
      try {
        await AsyncStorage.setItem('@user_Token', token)
      } catch (e) {
        // save error
      }
      console.log('Done.')
      console.log('User Registered!');
    }).catch(error => console.log(error));