I'm very new to react so please bare with me. I am creating a simple toDo list react application using localstorage. I have InputTask
component that keeps track of the input box state (where the user enters the task they want to add).
My goal right now is to add the task the user enters to localstorage then using another state called tasks
update all tasks to contain the new task the user entered. I feel like i'm overcomplicating this please help.
import React, { useEffect, useState } from "react";
// Imported Components below
import CurrentTasks from "./CurrentTasks";
function InputTask() {
// Initial array for storing list items
// Tracking state of input box
const [task, setTask] = useState();
const [tasks, setTasks] = useState([]);
function handleAddTask() {
// Create array to add to local storage of tasks
let allTasks = [];
// push new task to array
allTasks.push(task);
// add task to localstorage
localStorage.setItem("tasks", JSON.stringify(allTasks));
// update setTasks with new task (This contains all tasks prev)
setTasks(JSON.parse(localStorage.getItem("tasks")));
}
return (
<div className="container">
<div className="input-group mt-4">
<input
onChange={e => setTask(e.target.value)}
type="text"
className="form-control form-control-lg"
placeholder="Write task here..."
/>
<div className="input-group-append">
<button onClick={handleAddTask} className="btn btn-outline-secondary">
Add
</button>
</div>
</div>
<CurrentTasks />
</div>
);
}
export default InputTask;
The issue I am running into is that the tasks
state is always behind. So if i were to add "Make bed" to the task as the first item "Make bed" would not appear until I enter in a new task such as "fold cloths". Then, "fold cloths" will not appear until I enter in a new task... ect..