sooraj s pillai
sooraj s pillai

Reputation: 916

Clearing an item from AsyncStorage - React native

I'm new to react native currently i'm working on a project that needs to update a specific value in async storage. I tried by clearing an item from Asyncstorage using this code await AsyncStorage.removeItem(key); but when i used it console throws an error like this 'await' is only allowed within async functions . But i'm using an async function

  const getExceedCountData = async () => {
    const token = await AsyncStorage.getItem("@userToken")
    const exceedcount = await AsyncStorage.getItem("@exceedCount")
    if(!exceedcount){
        try {
        setLoading(true)
        axios
            .get(constants.BASE_URL + "getexceedcount?token=" +token)
            .then(response => {
                if(response.data.status == 1){
                    try {
                        await AsyncStorage.removeItem("@exceedCount");
                    }
                    catch(exception) {
                        console.log('Error Occured');
                    }
                    AsyncStorage.setItem("@exceedCount", response.data.result);
                    setExceedCount({ value:response.data.result, error: '' })
                }
            })
            .catch(error => {
                console.log(error);
            });
        } catch(error) {
            console.log(error);
        }
    }else{
        setExceedCount({ value:exceedcount, error: '' })
    }
  }

I don't know why this issue occured. Any help is appreciable.

Upvotes: 1

Views: 549

Answers (2)

The scope of the function inside .then is not declared as async. This should fix your problem:

.then(async response => {
    if(response.data.status == 1){
       try {
          await AsyncStorage.removeItem("@exceedCount");
       } catch(exception) {
          console.log('Error Occured');
       }
       AsyncStorage.setItem("@exceedCount", response.data.result);
       setExceedCount({ value:response.data.result, error: '' })
    }
})

Upvotes: 1

strdr4605
strdr4605

Reputation: 4352

You need to notate the function as async.

.then(async (response) => {
                if(response.data.status == 1){
                    try {
                        await AsyncStorage.removeItem("@exceedCount");
                    }
                    catch(exception) {
                        console.log('Error Occured');
                    }
                    AsyncStorage.setItem("@exceedCount", response.data.result);
                    setExceedCount({ value:response.data.result, error: '' })
                }
            })

Upvotes: 1

Related Questions