Cannot dispatch action after reading from async storage

This is my code

export const getAsyncStorage = () => async dispatch => {
    try {
        const asyncStorage = await AsyncStorage.getItem('settings');
        const asyncStorageObject = asyncStorage != null ? JSON.parse(asyncStorage) : null;
        console.log(asyncStorageObject) // this logs an object, as expected
        dispatch({ type: GET_ASYNC_STORAGE, payload: asyncStorageObject })
    } catch (e) {
        console.log('Error in getAsyncStorage writing to AsyncStorage', e)
    }
}

This is the error I get

Error in getAsyncStorage writing to AsyncStorage ReferenceError: payload is not defined

Why does it throw "Payload not defined"? That does not make any sense to me. Deleting this line

dispatch({ type: GET_ASYNC_STORAGE, payload: asyncStorageObject })

solves it. When I change this line

dispatch({ type: GET_ASYNC_STORAGE, payload: asyncStorageObject })

to

dispatch({ type: GET_ASYNC_STORAGE, foo: asyncStorageObject })

I still get the same payload message… Not sure what that means.
Here is how I write to AsyncStorage:

export const writeAsyncStorage = () => async dispatch => {
    try {
        const settings = {...}
        await AsyncStorage.setItem('settings', JSON.stringify(settings));
        dispatch({ type: WRITE_ASYNC_STORAGE, payload: true, })
    } catch (e) {
        console.log('Error in onIntroDone writing to AsyncStorage', e)
    }
}

And the reducer

import {
    GET_ASYNC_STORAGE,
    ...
} from '../constants/actions';

const initialState = {
    ...
    asyncStorage: {}
};

const settings = (state = initialState, action) => {
    switch (action.type) {
        ...
        case GET_ASYNC_STORAGE:
            return {
                ...state,
                asyncStorage: payload.asyncStorage
            }
        default:
            return state;
    }
}

export default settings;

89 thoughts on “Cannot dispatch action after reading from async storage”

Leave a Comment