Search code examples
typescriptredux-toolkit

How to access getState in redux toolkit in typescript?


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?


Solution

  • You can't assert types while destructuring objects. Also, you need to call getState before it can be asserted as AppState.

    You can do this instead:

    const getInitialDatapoints = createAsyncThunk(
            "userSlice/getInitDatapoints",
            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;
            }
        );