-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreducers.js
108 lines (89 loc) · 2.19 KB
/
reducers.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { createStore, combineReducers, bindActionCreators } from "redux";
const state = {
users: [
{
id: 1,
name: 'izhar'
},
{
id: 2,
name: 'mohammed'
},
{
id: 3,
name: "random"
}
],
todos: [
{
userId: 1,
todoId: 1,
name: 'learn nextJS'
},
{
userId: 1,
todoId: 2,
name: "learn express"
},
{
userId: 3,
todoId: 1,
name: "learn JS"
},
{
userId: 2,
todoId: 1,
name: "learn java"
}
]
}
const ADD_USER = 'add_user';
const EDIT_TODO = 'edit_todo';
// These functions are called as action creators
const add_user = (id, name) => (
{
type: ADD_USER,
userId: id,
userName: name
}
)
// These functions are called as action creators
const edit_todo = (userId, todoId, name) => (
{
type: EDIT_TODO,
userId: userId,
todoId: todoId,
name: name
}
)
//These are reducer functions
function userReducer(users = state.users, action) {
if (action.type == ADD_USER) {
let newUser = { id: action.userId, name: action.userName };
let newUsers = [ ...users, newUser ];
return newUsers;
}
return users;
}
//These are reducer functions
function todoReducer(todos = state.todos, action) {
if (action.type == EDIT_TODO) {
let newTodos = todos.map(todo => {
if (todo.todoId == action.todoId && todo.userId == action.userId) {
todo.name = action.name;
}
return todo;
})
return newTodos;
}
return todos;
}
// combineReducers :- used for combining multiple reducres
const combinedReducer = combineReducers({ users: userReducer, todos: todoReducer });
const store = createStore(combinedReducer, {});
//
const actions = bindActionCreators({ add_user ,edit_todo}, store.dispatch)
actions.add_user(10,'smartest')
actions.add_user(20,'Dummy')
actions.edit_todo(1,1,'explore shadcn !!!')
console.log(store.getState());