recoil-persist icon indicating copy to clipboard operation
recoil-persist copied to clipboard

AsyncStorage implementation issue.

Open dezudas opened this issue 3 years ago • 5 comments

will it be possible to provide an example for AsyncStorage when I tried it says "Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'hasOwnProperty' of null"

dezudas avatar Aug 23 '21 14:08 dezudas

same here

deargosep avatar Oct 08 '21 09:10 deargosep

Same here, any solution?

fervailanti avatar Dec 15 '21 12:12 fervailanti

You don't need to use this library to get simple persistence with Recoil and React Native. Just adapt the localForage example from the Recoil documentation, and you get (with TypeScript):

import {atom, AtomEffect, DefaultValue} from "recoil";

function persistAtom<T>(key: string): AtomEffect<T> {
  return ({setSelf, onSet}) => {
    setSelf(AsyncStorage.getItem(key).then(savedValue =>
      savedValue != null
        ? JSON.parse(savedValue)
        : new DefaultValue() // Abort initialization if no value was stored
    ));

    // Subscribe to state changes and persist them to localForage
    onSet((newValue, _, isReset) => {
      isReset
        ? AsyncStorage.removeItem(key)
        : AsyncStorage.setItem(key, JSON.stringify(newValue));
    });
  };
}

const myAtom =  atom({key: 'my-key', default: {}, effects_UNSTABLE: [persistAtom('my-async-storage-key')]})

Then wrap your RecoilRoot with a Suspense component:

      <React.Suspense fallback={<View><Text>Loading</Text></View>}>
        <RecoilRoot>
          {/* your app components */}
        </RecoilRoot>
      </React.Suspense>

fagerbua avatar Dec 31 '21 15:12 fagerbua

Despite the typings, it doesn't seem to support async getItem or setItem.

image

cuzzlor avatar Feb 14 '23 08:02 cuzzlor

I had to adapt the code from @fagerbua cause I was getting blank screens. This worked better for me, copying the latest recoil documentation:

function persistAtom<T>(key: string): AtomEffect<T> {
    return ({ setSelf, onSet, trigger }) => {
        const loadPersisted = async () => {
            const savedValue = await AsyncStorage.getItem(key);

            if (savedValue != null) {
                setSelf(JSON.parse(savedValue));
            }
        };

        // Asynchronously set the persisted data
        if (trigger === 'get') {
            loadPersisted();
        }

        // Subscribe to state changes and persist them to localForage
        onSet((newValue, _, isReset) => {
            isReset
                ? AsyncStorage.removeItem(key)
                : AsyncStorage.setItem(key, JSON.stringify(newValue));
        })
    }
}

const myAtom =  atom({key: 'my-key', default: {}, effects_UNSTABLE: [persistAtom('my-async-storage-key')]})

ipoogleduck avatar Aug 15 '23 18:08 ipoogleduck