I'm trying to make a to-do app with react. It has basic functionalities: item adding, item removing, and complete task. In my code, functionalities working clearly but when I click the complete button, and the same time remove that item it is working buggy. Item removes but completed checkbox adding the next item.
Code Section: App.js
import './App.css';
import Header from './components/Header';
import List from './components/List';
import React, { useState, useEffect } from 'react';
function App() {
const [elements, setElements] = useState([]);
useEffect(() => {
console.log(elements);
}, [elements]);
const setElement = (element) => {
setElements([...elements, element]);
}
const completeElement = (index) => {
let array = [...elements];
array[index].isCompleted = !array[index].isCompleted;
setElements(array);
}
const deleteElement = (index) => {
let array = [...elements];
array.splice(index, 1);
setElements(array);
}
return (
<div className="todoapp">
<Header save={setElement} />
<List elements={elements} complete={completeElement} remove={deleteElement} />
</div>
);
}
export default App;
List.js:
{elements.map((item, index) => {
const status = item.isCompleted ? "completed" : "";
return(
<li className={status} key={index}>
<div className="view">
<input className="toggle" type="checkbox" onClick={() => {complete(index)}} />
<label>{item.text}</label>
<button className="destroy" onClick={() => {remove(index)}}></button>
</div>
</li>
);
})}
On List.js, className={status} working buggy.
Thanks for help.