I am making a simple React app with goals and want to be able to mark them off as complete but am having trouble with setting complete to true once I click on the complete button. Here's my code: I'm currently able to add and delete the goals, but complete is staying as false.
App.jsx:
const [goals, setGoals] = useState([]);
const [goal, setGoal] = useState({
complete: false
})
function addGoal(newGoal) {
setGoals((prevGoals) => {
return [...prevGoals, newGoal];
});
}
function deleteGoal(id) {
setGoals((prevGoals) => {
return prevGoals.filter((goalItem, index) => {
return index !== id;
});
});
}
function completeGoal(id) {
setGoals(
goals.map(goal => {
if (goal.id === id) {
return {
complete: !goal.complete
}
}
return goal;
})
)
}
return (
<div>
<Header />
<CreateGoal onAdd={addGoal} />
{goals.map((goalItem, index) => {
return (
<Goal
key={index}
id={index}
title={goalItem.title}
content={goalItem.content}
onDelete={deleteGoal}
onComplete={completeGoal}
/>
);
})}
</div>
);
}
Here is after the goal is added and displayed with the buttons for completing and deleting.
Goal.jsx:
function Goal(props) {
function handleClick() {
props.onDelete(props.id);
}
function handleGoal() {
props.onComplete(props.id);
}
return (
<div className="note">
<h1>{props.title}</h1>
<p>{props.content}</p>
{/* <button className="fas fa-check"></button> */}
<button onClick={handleGoal} className="complete-btn">
<i className="fas fa-check"></i>
</button>
<button onClick={handleClick}>
<i className="far fa-trash-alt">
</i></button>
</div>
)
}
export default Goal
Update your completeGoal function as below to set complete true
function completeGoal(id) {
setGoals((prev) =>
prev.mapmap((goal) => (goal.id === id ? { ...goal, complete: true } : { ...goal })),
);
}