@reduxjs/toolkit
has these 4 functions to make your dev life easier
1configureStore() // wraps createStore() + DevTools + Middleware (redux-thunk)
2createAction() // Creates an Action creator by taking an action type. Generated function takes a single argument that becomes action.payload
3createReducer() // Creates a reducer function
4createSlice()
And react-redux
has these 2 hooks that we’ll use
1useSelector() // lets you extract data from the Redux store state, using a selector function
2useDispatch() // lets you dispatch Actions
And in React we’ll use hooks too
1useState() // handling 'local' component state
2useEffect() // lifecycle events and side effects
1// State tree
2{
3 todos : [
4 {
5 id: uuid(), // import * as uuid from 'uuid/v4'
6 createdAt: new Date().toISOString(),
7 title: 'Create a React todo list app',
8 description: 'Use redux toolkit and react-redux hooks', // optional
9 status: 'In Progress', // 3 Statuses total: Done, In Progress, Pending
10 list: 'Dev'
11 },
12 {},
13 {}
14 ],
15 lists: [
16 {
17 id: v4(),
18 createdAt: new Date().toISOString()
19 title: 'Dev'
20 description: 'Code and development related tasks' // optional
21 },
22 {},
23 {}
24 ],
25 filter: 'showAll'/'showDone'/'showPending'/'showInProgress'
26}
1// Actions
2todos/add
3todos/update
4todos/remove
Create reducers first, Actions next. With createReducer()
you can actually pass the createAction()
directly and make creating the reducer and action a single step.
Add todo item
1import { createAction } from '@reduxjs/toolkit'
2import v4 from 'uuid/v4'
3
4const addTodo = createAction("todos/add", function prepare(title, description, status = 'Pending', list) {
5 return {
6 payload: {
7 id: v4(),
8 createdAt: new Date().toISOString()
9 title,
10 description,
11 status, // unless you allow setting a status when creating a todo, this is going to be 'Pending' by default
12 list
13 }
14 };
15});
1import { useDispatch } from 'react-redux'
2
3useDispatch(addTodo('Write more docs'))