Skip to content

Instantly share code, notes, and snippets.

@danielepolencic
Created September 9, 2020 03:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielepolencic/21ec48fe1d829fb853abbec3f5d4b06b to your computer and use it in GitHub Desktop.
Save danielepolencic/21ec48fe1d829fb853abbec3f5d4b06b to your computer and use it in GitHub Desktop.
Redux toolkit + redux-thunk end-to-end demo
import { createAsyncThunk, createSlice, configureStore, Dispatch, AnyAction } from '@reduxjs/toolkit'
import thunk, { ThunkDispatch } from 'redux-thunk'
const userAPI = {
async fetchById(id: string) {
return new Promise<{ data: number }>(resolve =>
setTimeout(() => {
resolve({ data: 1 })
}, 4000),
)
},
}
// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId: string, thunkAPI): Promise<number> => {
const response = await userAPI.fetchById(userId)
return response.data
},
)
// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: builder => {
builder.addCase(fetchUserById.fulfilled, (state, action) => {
console.log('fullfilled', action)
})
builder.addCase(fetchUserById.rejected, (state, action) => {
console.log('rejected', action)
})
builder.addCase(fetchUserById.pending, (state, action) => {
console.log('pending', action)
})
// // Add reducers for additional action types here, and handle loading state as needed
// [fetchUserById.fulfilled.toString()]: (state, action) => {
// // Add user to the state array
// console.log(action)
// }
},
})
const store = configureStore({
reducer: {
user: usersSlice.reducer,
},
middleware: [
thunk,
logger({
ignore: [],
}),
],
})
type Store = typeof store
type State = ReturnType<typeof store.getState>
function logger({ ignore }: { ignore: string[] }) {
return (store: any) => {
return (next: Dispatch<AnyAction>) => (action: AnyAction) => {
if (!ignore.some(it => action.type.startsWith(it))) {
console.log(`✉️ [${action.type}]`, action.payload ?? '')
}
return next(action)
}
}
}
const dispatch: ThunkDispatch<State, void, AnyAction> = store.dispatch
// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById('123'))
@SreejithNS
Copy link

Thank you so much for the Line:74 ❤❤❤❤

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment