Home > Mobile >  How to access getState in redux toolkit in typescript?
How to access getState in redux toolkit in typescript?

Time:12-26

I have an createAsyncThunk operation and want to access getState inside the toolkit. I am not sure about how to cast getState type in typescript:

export const getInitialDatapoints = createAsyncThunk(
  'userSlice/getInitDatapoints',
  async (args, { getState as AppState }) => {
    const geoData = await getLocationData();
    const googleData = getState().userSlice;
    const response = await updateUserData(1);
    return response.data;
  }
);

where AppStore is:

export type AppState = ReturnType<typeof store.getState>;

I get this error:

Property 'AppState' does not exist on type 'GetThunkAPI<{}>'

Can anyone help in solving this issue?

CodePudding user response:

You can't cast types while destructuring objects. Also, you need to call getState before you can cast it to AppState.

You can do this instead:

const getInitialDatapoints = createAsyncThunk(
        "userSlice/getInitDatapoints",
        // you could also just stick to { getState }; call and
        // cast it in the line below.
        async (args, api) => {
            const appState = api.getState() as AppState
            const geoData = await getLocationData();
            const googleData = appState.userSlice;
            const response = await updateUserData(1);
            return response.data;
        }
    );
  • Related