简体   繁体   中英

Wipe AsyncStorage in react native

I notice that I am wasting a certain amount of time debugging redux actions that I am persisting to AsyncStorage in react-native thanks to redux-persist . Sometimes I'd just like to wipe AsyncStorage to save some development time and try with fresh data.

EDIT: Best case the solution should work on simulators and real devices, iOS and Android. Maybe there are different work arounds for different platforms.

Thanks

尝试使用clear()函数擦除所有客户端、库等的所有AsyncStorage

clearAsyncStorage = async() => {
    AsyncStorage.clear();
}

This function can be applied anywhere on the code base to clear AsyncStorage . For example, here is how it can be called on a <Button> component.

<Button onPress={this.clearAsyncStorage}>
  <Text>Clear Async Storage</Text>
</Button>

You can clear AsyncStorage easily without touching your source code. Using react native debugger ; and in the devtools console type

$reactNative.AsyncStorage.clear();

or to call it in RN's normal debugger with clear() you can put this in...

if (__DEV__) {
   global.clear = () => {
     AsyncStorage.clear().then(() => console.log('Cleared'))
   }
}

IMHO, all the answers referring to AsyncStorage.clear() are wrong, since, as the documentation say:

Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this; use removeItem or multiRemove to clear only your app's keys.

The correct answer may be found here :

Here is a simple way of doing it:

clearAllData() {
    AsyncStorage.getAllKeys()
        .then(keys => AsyncStorage.multiRemove(keys))
        .then(() => alert('success'));
}

redux-persist comes with a purge() callback. You can call that in a debug menu somewhere if you choose.

Working with AsyncStorage threw a Reference Error on my side :

ReferenceError: AsyncStorage is not defined

I finally found in the React Native Debuguer documentation a mention about

$reactNative.*

(For RN >= 0.56)

Which led mean to this snippet to wipe out all of my local storage :

clearAllData = () => {
    $reactNative.AsyncStorage.getAllKeys()
        .then(keys => $reactNative.AsyncStorage.multiRemove(keys))
        .then(() => alert('success'));
}

Then just clearAllData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM