Search code examples
reactjsreact-nativeuse-effectasyncstoragepersistent-storage

React Native AsyncStorage for iOS switch state not persisting


I am trying to persist a switch button state by using AsyncStorage to store a boolean but it's not working. Whenever I leave that screen or close the app and return to that screen, the state of the switch resets to the default instead of reading from the AsyncStorage value.

Here are the AsyncFunctions I have defined:

export async function setPersistedSwitchState(newValue) {
    await AsyncStorage.setItem(
        'switchState',
        JSON.stringify(newValue),
    );
}

export async function getPersistedSwitchState() {
    const switchState = JSON.parse(
        await AsyncStorage.getItem('switchState'),
    );
    return switchState;
}

Here is my code on the toggle switch screen:

export function switchButtonScreen() {
    let currentState = false;
    const [toggleState, setToggleState] = useState(
        currentState
    );

    useEffect(() => {
        const getSwitchState = async () => {
          try {
            const value = await getPersistedSwitchState()
            return value != null ? value : false;
          } catch(e) {
            console.log(e);
          }
        };
        currentState = fetchPersistedSwitchState();
    }, [toggleState]);


    const toggleSwitch = async () => {
        setToggleState(!toggleState);
        if (!toggleState) {
            await setPersistedSwitchState(true);
        } else await setPersistedSwitchState(false);
    };

    return (

                    <SwitchButton
                        enabled={toggleState}
                        onChange={toggleSwitch}
                    />

    );
}

...

Any help would be appreciated. Thank you in advance.


Solution

  • As @emkarachchi in the comment pointed out, you need to us setToggleState(currentState) at the end of your useEffect call. The state uses currentState only at the first loading of your screen.

    For setPersistedSwitchState better straight use your togglestate variable, so you do not need the ifs, so setPersistedSwitchState(!toggleState).