0

I'm using React and I have a list, and each item in the list with a check.

And I want that when there is at least one check in true, a button is shown (it is to delete all the checks).

enter image description here


enter image description here

I am using useReducer() to store the list.

This is my code, but it doesn't work.

const init = () => {
    return JSON.parse(localStorage.getItem('todos')) || [];
}

const [todos, dispatch] = useReducer(todoReducer, [], init)
const [todoDelete, setTodoDelete] = useState(0)
useEffect(() => {       
        localStorage.setItem('todos', JSON.stringify(todos));
 
        todos.map(todo => {
            todo.check ? setTodoDelete(todoDelete+1) : setTodoDelete(todoDelete-1);
        })
    }, [todos])

returm (

   code...
   {
     (todoDelete!==0) 
                && <button
                    className='btn btn-danger btn-sm h-50' onClick={handleDeleteChecked}>
                    Delete
                </button> 
   }
)

What interests me is that when there is more than one check, a button is added, otherwise it is removed. How do i do it?

Ken White
  • 123,280
  • 14
  • 225
  • 444

1 Answers1

0

Change this

            todo.check ? setTodoDelete(todoDelete+1) : setTodoDelete(todoDelete-1);

To this

            todo.check ?? setTodoDelete(prev => prev+1);
Abdul Mahamaliyev
  • 750
  • 1
  • 8
  • 20