Right now I've got these actions that I use for an upload thunk's lifecycle.
type UPLOAD_START = PayloadAction<void>
type UPLOAD_SUCCESS = PayloadAction<{ src: string, sizeKb: number }>
type UPLOAD_FAILURE = PayloadAction<{ error: string }>
And I'd like to convert it to a createAsyncThunk call, assuming it will reduce the code. But will it?
From the example on https://redux-toolkit.js.org/api/createAsyncThunk it should be something like:
const uploadThumbnail = createAsyncThunk(
'mySlice/uploadThumbnail',
async (file: File, thunkAPI) => {
const response = await uploadAPI.upload(file) as API_RESPONSE
return response.data // IS THIS THE payload FOR THE fulfilled ACTION ?
}
)
This is how I would handle the life cycle actions?
const usersSlice = createSlice({
name: 'mySlice',
initialState: // SOME INITIAL STATE,
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[uploadThumbnail.pending]: (state,action) => {
// HANDLE MY UPLOAD_START ACTION
},
[uploadThumbnail.fulfilled]: (state, action) => {
// HANDLE MY UPLOAD_SUCCESS ACTION
},
[uploadThumbnail.rejected]: (state, action) => {
// HANDLE MY UPLOAD_FAILURE ACTION
},
}
})
QUESTION
I'm assuming the return of the createAsyncThunk async handler is the payload for the fulfilled action, is that right?
But how can I set the payload types for the pending and the rejected actions? Should I add a try-catch block to the createAsyncThunk handler?
Is this the correlation I should be doing?
pending === "UPLOAD_START"fulfilled === "UPLOAD_SUCCESS"rejected === "UPLOAD_FAILURE"
Obs: From the pattern I'm imagining, it doesn't look I'll be writing any less code than what I'm already doing with three separate actions and handling them in my regular reducers (instead of doing it on the extraReducers prop). What is the point of using the createAsyncThunk in this case?