Why redux toolkit boolean toggle doesn't work?

Viewed 1146

I keep a boolean value called "isCompleted", but it doesn't work. It becomes true when false, but does not become false again afterwards. The Redux action and the function I wrote are as follows. What could be the reason for this? Thanks for advance.

const todoSlice = createSlice({
    name: 'todos',
    initialState: {
        todos: []
    },
    reducers: {
        addTodo: (state, action) => {
            state.todos = [...state.todos, action.payload]
        },
        deleteTodo: (state, action) => {
            state.todos = action.payload
        },
        completedTodo: (state, action) => {
            state.todos = action.payload
        }
    }
})

export const {
    addTodo,
    deleteTodo,
    completedTodo
} = todoSlice.actions

export const selectUser = (state) => state.todos;

export const store = configureStore({
    reducer: todoSlice.reducer
})
const Todo = () => {
    const user = useSelector(selectUser);
    const dispatch = useDispatch();

    const checkHandler = (id) => {
        const dene = user.map((item) => {
            if (item.id === id) {
                const comp = item.isCompleted
                return {
                    ...item,
                    isCompleted: !item.isCompleted
                };
            }
        })
        dispatch(completedTodo({dene}))
    }

    const deleteHandler = (id) => {
        const filteredTodos = user.filter(todo => todo.id !== id)
        dispatch(deleteTodo(filteredTodos))
    }

    return (
        user.map((todo) => {
            return <li key={todo.id} className={todo.isChechked ? "todo-item checked" : "todo-item"}>
                <p>{todo.title}</p>
                <div className="btns">
                    <IconButton onClick={() => deleteHandler(todo.id)} className="trash-btn" aria-label="delete">
                        <DeleteIcon />
                    </IconButton>
                    <IconButton onClick={() => checkHandler(todo.id)} className="complete-btn" aria-label="delete">
                        <CheckIcon />
                    </IconButton>
                </div>
            </li>
        })
    )
}

export default Todo

What is the best boolean toggle method for Redux?

1 Answers

You forgot to return the other todo items in the .map() function. It will cause the state.todos incorrect.

const dene = user.map((item) => {
  if (item.id === id) {
    return {
      ...item,
      isCompleted: !item.isCompleted,
    };
  }
  // notice here
  return item;
});

dispatch(completedTodo(dene));

Pass the dene to action creator directly, you can get the dene in reducer from action.payload.

Related