Shivam Sahil
Shivam Sahil

Reputation: 4921

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?

Upvotes: 1

Views: 2339

Answers (1)

Shockch4rge
Shockch4rge

Reputation: 458

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;
        }
    );

Upvotes: 4

Related Questions