-
Notifications
You must be signed in to change notification settings - Fork 0
/
counterSlice.js
46 lines (39 loc) · 988 Bytes
/
counterSlice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
const initialState = {
value: 0,
};
const surpriseFactor = 50;
export const incrementBySurprise = createAsyncThunk(
'counter/incrementBySurprise',
async () => {
const rand =
Math.round(Math.random() * surpriseFactor) - surpriseFactor * 0.5;
return rand;
}
);
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
decrementByAmount: (state, action) => {
state.value -= action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(incrementBySurprise.fulfilled, (state, action) => {
state.value += action.payload;
});
},
});
export const { increment, decrement, incrementByAmount, decrementByAmount } =
counterSlice.actions;
export default counterSlice.reducer;