Easy-peasy: Persist not working with AsyncStorage (React Native)

Created on 16 Feb 2020  路  5Comments  路  Source: ctrlplusb/easy-peasy

easy-peasy: v3.2.0 & v3.3.0
expo: v~36.0.0

When using AsyncStorage, the entire expo app crashes.

IMG_0339

Only when passing AsyncStorage to the persist config, like so. Putting 'localStorage' does not error.

import { AsyncStorage } from 'react-native';
import { createStore, persist } from 'easy-peasy';

export default createStore(
  persist(store, {
    storage: AsyncStorage,
  }),
);

Maybe down to not stringifying the values: https://stackoverflow.com/questions/49491485/error-react-native-ios-exception-nsdictionarym-length-unrecognised-select

Most helpful comment

solution is to slightly tweak the storage to serialize:

import AsyncStorage from '@react-native-community/async-storage'

const storage = {
  async getItem(key) {
    return JSON.parse(await AsyncStorage.getItem(key))
  },
  setItem(key, data) {
    AsyncStorage.setItem(key, JSON.stringify(data))
  },
  removeItem(key) {
    AsyncStorage.removeItem(key)
  }
}

export default storage

All 5 comments

None of the persist methods for react native have worked for us either.

@systemlevel How are you planning on implementing offline support instead?

@ctrlplusb do you have any clue on this?

solution is to slightly tweak the storage to serialize:

import AsyncStorage from '@react-native-community/async-storage'

const storage = {
  async getItem(key) {
    return JSON.parse(await AsyncStorage.getItem(key))
  },
  setItem(key, data) {
    AsyncStorage.setItem(key, JSON.stringify(data))
  },
  removeItem(key) {
    AsyncStorage.removeItem(key)
  }
}

export default storage

solution is to slightly tweak the storage to serialize:

import AsyncStorage from '@react-native-community/async-storage'

const storage = {
  async getItem(key) {
    return JSON.parse(await AsyncStorage.getItem(key))
  },
  setItem(key, data) {
    AsyncStorage.setItem(key, JSON.stringify(data))
  },
  removeItem(key) {
    AsyncStorage.removeItem(key)
  }
}

export default storage

Thanks! I had to add async in front of setItem and removeItem or else I would get an error "Cannot read property 'catch' of undefined" from the writeStatedState function of createPersistoid.js in redux-persist.

This is what worked for me:

import AsyncStorage from '@react-native-community/async-storage'

const storage = {
  async getItem(key) {
    return JSON.parse(await AsyncStorage.getItem(key))
  },
  async setItem(key, data) {
    AsyncStorage.setItem(key, JSON.stringify(data))
  },
  async removeItem(key) {
    AsyncStorage.removeItem(key)
  }
}

export default storage
Was this page helpful?
0 / 5 - 0 ratings

Related issues

lishine picture lishine  路  6Comments

gino8080 picture gino8080  路  5Comments

ifyoumakeit picture ifyoumakeit  路  5Comments

djgrant picture djgrant  路  6Comments

vincentjames501 picture vincentjames501  路  6Comments