33
loading...
This website collects cookies to deliver better user experience
Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.
Centralizing your application's state and logic enables powerful capabilities like undo/redo, state persistence, and much more.
array.push()
.In a very large web app, where we have to fetch data constantly from an API, it's not always easy to add those to existing data without accidentally mutating the state.
Boilerplate codes
const ADD_TODO = 'ADD_TODO';
const addTodo = (title) => {
return {
type: ADD_TODO,
payload: title,
}
}
const todoReducer = (state=[],action) => {
switch(action.type){
case ADD_TODO:
return [action.payload,...state];
default:
return state;
}
}
rootReducer = combineReducers({todo: todoReducer})
Includes utilities to simplify common use cases like store setup, creating reducers, immutable update logic, and more.
Takes inspiration from libraries like Immer and Autodux to let you write "mutative" immutable update logic, and even create entire "slices" of state automatically.
Provides good defaults for store setup out of the box, and includes the most commonly used Redux addons built-in.
createSlice()
in which we can mention our action name
, initials state
, reducers
and the state for async data fetching i.e pending, fulfilled, or rejected.import { createSlice } from '@reduxjs/toolkit'
const initialState = []
const todoSlice = createSlice({
name: 'todo',
initialState,
reducers: {
addTodo: (state,action) => {
state.push(action.payload)
},
},
})
export const todoActions = todoSlice.actions
export default todoSlice.reducer
createAsyncThunk()
for async thunk functions which we have to manually export action.const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
pending
, rejected
or fulfilled
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
[fetchUserById.rejected]:(state,action) => {
//Some functions or notifications if there is an error
},
[fetchUserById.pending]:(state,action) => {
//Some functions or notifications if req is going through
},
[fetchUserById.fulfilled]:(state,action) => {
//Some functions or notifications is res is back as successful
},
},
})