Details: I am using @reduxjs/toolkit and reactjs to build a simple todo app. I use @reduxjs/toolkit. And I want to add a filter list by All and completed \ not completed.
Questions: How I can add filter list to this todo list (All and completed \ not completed)?
todoSlice.js:
import { createSlice } from '@reduxjs/toolkit';
const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [
{
id: 1,
completde: false,
title: 'todo 1',
completed: false,
},
{
id: 2,
completde: true,
title: 'todo 2',
completed: false,
},
],
},
reducers: {
addTodo(state, action) {
state.todos.push({
id: new Date().toISOString(),
title: action.payload.title,
});
},
toggleTodo(state, action) {
const toggleTodoItem = state.todos.find(
(todo) => todo.id === action.payload.id
);
toggleTodoItem.completed = !toggleTodoItem.completed;
},
removeTodo(state, action) {
state.todos = state.todos.filter((todo) => todo.id !== action.payload.id);
},
filterTodo(state, action) {
// state.filterKey = action.payload.key;
console.log(action.payload);
},
},
});
const { actions, reducer } = todoSlice;
export const { addTodo, removeTodo, toggleTodo, filterTodo } = actions;
export default reducer;
FilterTodo.js:
import { useDispatch } from 'react-redux';
import { filterTodo } from './todoSlice';
export default function TodoFilter({ key }) {
const dispatch = useDispatch();
return (
<>
<button onClick={dispatch(filterTodo('ALL'))}>All</button>
<button onClick={dispatch(filterTodo('COMPLETED'))}>Completed</button>
<button onClick={dispatch(filterTodo('NOT_COMPLETED'))}>
Not completed
</button>
</>
);
}
TodoList.js:
import TodoItem from './TodoItem';
import { useSelector } from 'react-redux';
export default function TodoList() {
const todos = useSelector((state) => state.todos.todos);
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} {...todo} />
))}
</ul>
);
}
... ... ....