Redux toolkit provides createAction
helper method. I am having trouble referring actions created with createAction
as type.
For example:
const getData = createAction<PayloadAction<number>>('user/getData')
function* exampleSaga(action: ?) {
...
}
How can I tell exampleSaga
that action
is of type getData
?
To see how I've tried doing it, refer the below (example) code and see comments for the problem I am facing:
reducer.ts
import { createAction, PayloadAction } from '@reduxjs/toolkit';
export const getData = createAction<PayloadAction<number>>('user/getData');
const userSlice = createSlice({
name: userSliceName,
initialState,
reducers: {
getUser(state: IUserState): void {
state.loading = true;
state.error = null;
},
getUserSuccess(state: IUserState, action: PayloadAction<{ user: IUser }>): void {
const { user } = action.payload;
state.user = user;
state.loading = false;
state.error = null;
},
getUserFailure(state: IUserState, action: PayloadAction<string>): void {
state.loading = false;
state.error = action.payload;
},
},
});
export type UserSaga = Generator<
| CallEffect<IUser>
| PutEffect<typeof getUserSuccess>
| PutEffect<typeof getUserFailure>
| ForkEffect<never>
>;
sagas.ts
import { UserSaga, getData } from './reducer.ts';
// For the following fetchUser saga arguments, how can I define that 'action' is of type getData, imported from the above 'reducer.ts' file.
function* fetchUser(action: PayloadAction<typeof getData>): UserSaga {
try {
const userId = action.payload;
// Problem is here
// I expect userId to be of type number, whereas it is:
// ActionCreatorWithPayload<{payload: number, type: string}>
...
} catch (e) {
...
}
}
function* userSaga(): UserSaga {
const pattern: any = getData.type;
yield takeLatest(pattern, fetchUser);
}
This is how you will get it using return type of your getData.
function* exampleSaga(action: ReturnType<typeof getData>) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With