Search code examples
reactjsreact-nativeasyncstoragedata-persistence

Persisting data if none exists for a certain key using AsyncStorage


I'm trying to set up a function where I first check to see if I have a value for a certain key, and if I do not, I use the axios library to get a value from the web and persist it as that key's value instead. Here is my code:

async getName() {
    try {
        const value = await AsyncStorage.getItem('dummy'); //the value should be a JSON object
        if (value !== null){
            return value.name;
        }
        else {
            axios.get('https://api.github.com/users/dummy')
                .then(function (response) {
                    console.log(response);
                    try {
                        await AsyncStorage.setItem('dummy', 'dummyval');
                    } catch (error) {
                        console.log(error);
                    }
                    return(response.name);
                })
                .catch(function (error) {
                    console.log('Error fetching name: ' + error.response);
                });
        }
    } catch (error) {
        console.log(error);
    }

I'm pretty new to React Native, so I'm sure this looks like a mess. I know I must be doing something wrong because I keep getting a syntax error on the second use of await. Does anyone know how to properly structure these calls?


Solution

  • You need to declare axios's success handler using async keyword. In your code, you have written like .then(function (response), this should be changed to .then(async function (response).

    Consider following changes.

    async getName() {
     try {
        const value = await AsyncStorage.getItem('dummy'); //the value should be a JSON object
        if (value !== null){
            return value.name;
        }
        else {
            axios.get('https://api.github.com/users/dummy')
                .then(async function (response) {
                    console.log(response);
                    try {
                        await AsyncStorage.setItem('dummy', 'dummyval');
                    } catch (error) {
                        console.log(error);
                    }
                    return(response.name);
                })
                .catch(function (error) {
                    console.log('Error fetching name: ' + error.response);
                });
        }
     } catch (error) {
        console.log(error);
     }
    }
    

    Hope this helps!