install redux toolkit on react code example
Example 1: redux toolkit
import { createSlice } from '@reduxjs/toolkit';
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export const selectCount = state => state.counter.value;
export default counterSlice.reducer;
Example 2: redux toolkit
import { createSlice } from '@reduxjs/toolkit'
const slice = createSlice({
name: 'user',
initialState: {
user: null,
},
reducers: {
loginSuccess: (state, action) => {
state.user = action.payload;
},
logoutSuccess: (state, action) => {
state.user = null;
},
},
});
export default slice.reducer
const { loginSuccess, logoutSuccess } = slice.actions
export const login = ({ username, password }) => async dispatch => {
try {
dispatch(loginSuccess({username}));
} catch (e) {
return console.error(e.message);
}
}
export const logout = () => async dispatch => {
try {
return dispatch(logoutSuccess())
} catch (e) {
return console.error(e.message);
}
}