Mer sofistikerad
Förutom Redux Toolkit måste vi installera React-Redux som kommunicerar mellan vår React app och Redux store!
“- Configuring a Redux store is too complicated
- I have to add a lot of packages to get Redux to do anything useful
- Redux requires too much boilerplate code”
En slags mellanhand som förenklar processen
"Redux Toolkit architecture is to break each functionality in a feature slice and as more and more features are added we can than accessing each “slice” of data. If we think in terms of food the Redux is a vanilla flavor icecream one flavor our store holds all the data. In our Redux Toolkit, our store is more like a pizza, our “slice” is like a slice of pizza and all the slices make up our store."
"Redux Toolkit also runs the Immer library https://github.com/immerjs/immer which lets us write the code in a mutative way — we create the next immutable state tree by simply modifying the current tree. "
Läs mer här! https://redux-toolkit.js.org/usage/immer-reducers
import { createSlice } from '@reduxjs/toolkit';
const userSlice = createSlice({
name: 'user',
initialState: {
currentUser: null,
users: []
},
reducers: {
setCurrentUser: (state, action) => {
state.currentUser = action.payload;
},
setUsers: (state, action) => {
state.users = action.payload;
},
addUser: (state, action) => {
state.users.push(action.payload);
}
}
});
export const { setCurrentUser, setUsers, addUser } = userSlice.actions;
export default userSlice.reducer;
# REDUX TOOLKIT
import { createSlice } from '@reduxjs/toolkit';
const postSlice = createSlice({
name: 'post',
initialState: {
posts: []
},
reducers: {
setPosts: (state, action) => {
state.posts = action.payload;
},
addPost: (state, action) => {
state.posts.push(action.payload);
},
deletePost: (state, action) => {
state.posts = state.posts.filter(post => post.id !== action.payload);
}
}
});
export const { setPosts, addPost, deletePost } = postSlice.actions;
export default postSlice.reducer;
# REDUX TOOLKIT
import { configureStore } from '@reduxjs/toolkit';
import userReducer from './userSlice';
import postReducer from './postSlice';
const store = configureStore({
reducer: {
user: userReducer,
post: postReducer
}
});
export default store;
# REDUX TOOLKIT
Antingen per component eller per feature
Utforska när ni ser behov i projektet