Can't persist state in React Native using easy-peasy

534 Views Asked by At

I'm getting the following error, when passing AsyncStorage as the storage engine:

WARN  Possible Unhandled Promise Rejection (id: 0):
Error: [AsyncStorage] Passing null/undefined as value is not supported. If you want to remove value, Use .removeItem method instead.
Passed value: undefined
Passed key: [EasyPeasyStore][0]

Here's my store declaration:

import { action, createStore, persist } from "easy-peasy";
import AsyncStorage from "@react-native-async-storage/async-storage";

const store = createStore(
    persist({
        ...my state goes here
    }, {
        storage: AsyncStorage
    })
);
2

There are 2 best solutions below

0
On

Try adding the allow property

const store = createStore(
persist({
    ...my state goes here
}, {
    allow: ['state attributes here ex. user'],
    storage: AsyncStorage
})

);

0
On

After a lot of time spent in debugging and searching through the GitHub issues, this is the solution I have found. Works like a charm here. Also, you need to allow which state variables are to be persisted.

import { action, createStore, persist } from "easy-peasy";
import AsyncStorage from "@react-native-async-storage/async-storage";

const store = createStore(
    persist({
        ...my state goes here
    }, {
        storage: {
            getItem: async function (key){
                console.log("GET_ITEM: ", key);
                const value = await AsyncStorage.getItem(key);
                return JSON.parse(value);
            },
            setItem: function (key, value){
                console.log("SET_ITEM: ", key, value);
                AsyncStorage.setItem(key, JSON.stringify(value))
            }
        },
        allow: ['Names of the state variables to be persisted goes here']
    })
);