aboutsummaryrefslogtreecommitdiffstats
path: root/public/projects/react-small-apps/apps/todos/src/store/users/users.slice.js
blob: ecce733bce041009be8ce5c7c7673673c2db7d98 (plain)
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
import { createSlice, nanoid } from "@reduxjs/toolkit";

export const usersSlice = createSlice({
  name: "users",
  initialState: [
    {
      id: "demo",
      createdAt: new Date().toISOString(),
      username: "Demo",
      email: "demo@email.com",
      password: "demo",
    },
  ],
  reducers: {
    addUser: {
      reducer: (state, action) => {
        state.push(action.payload);
      },
      prepare: (username, email, password) => {
        const id = nanoid();
        const createdAt = new Date().toISOString();
        return { payload: { id, username, email, password, createdAt } };
      },
    },
    deleteUser: (state, action) => {
      state.filter((user) => user.id !== action.payload);
    },
    updateUser: (state, action) => {
      state.map((user) => {
        if (user.id !== action.payload.id) return user;
        return { ...user, ...action.payload };
      });
    },
  },
});

export const { addUser, deleteUser, updateUser } = usersSlice.actions;

export default usersSlice.reducer;