aboutsummaryrefslogtreecommitdiff
path: root/src/features/todo/reducer.js
blob: a13810b656285015499d318daefea5d13e77144d (plain) (blame)
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
import { createSlice } from "@reduxjs/toolkit";

export const todo_slice = createSlice({
    name: "todo_list",
    initialState: {
        todos: [],
        last_id: 0,
    },

    reducers: {
        add_todo: (state, action) => {
            state.todos = [
                ...state.todos,
                {
                    id: ++state.last_id,
                    text: action.payload.text,
                    due_date: action.payload.due_date,
                    done: action.payload.done,
                    priority: action.payload.priority,
                    creation_date: action.payload.creation_date,
                },
            ];
        },

        change_done: (state, action) => {
            let selected_todo = state.todos.findIndex(
                (x) => x.id == action.payload.id
            );
            if (selected_todo == -1) return;

            state.todos[selected_todo].done = action.payload.done;
        },

        remove_todo: (state, action) => {
            state.todos = state.todos.filter(
                (todo) => todo.id != action.payload
            );
        },

        edit_todo: (state, action) => {
            let selected_todo = state.todos.findIndex(
                (x) => x.id == action.payload.id
            );
            if (selected_todo == -1) return;

            state.todos[selected_todo].text = action.payload.text;
            state.todos[selected_todo].due_date = action.payload.due_date;
            state.todos[selected_todo].done = action.payload.done;
            state.todos[selected_todo].priority = action.payload.priority;
        },
    },
});

export const { add_todo, change_done, remove_todo, edit_todo } =
    todo_slice.actions;

export const select_todos = (state) => state.todo_list.todos;
export const select_last_index = (state) => state.todo_list.last_id;

export default todo_slice.reducer;