I am currently building “To Do” web app, using ReactJS as Frontend and Django as Backend, and use axios to fetch requests.
I want a feature into my app that stores the “ToDo tasks” locally as the user updates them, and not lose it whenever the browser got refreshed or accidentally got exited.
I am using hooks and useEffect to store data locally. Whenever the browser is refreshed, the local data are washed by the database. This is snippet of my code. OR you can review the code here
const [taskEdits, setTaskEdits] = useState({});
useEffect(() => {
const storedEdits = JSON.parse(localStorage.getItem("taskEdits")) || {};
axios
.get("/tasks/")
.then((res) => {
const fetchedTasks = res.data;
const mergedTasks = fetchedTasks.map((task) => {
if (storedEdits[task.id]) {
return { ...task, title: storedEdits[task.id] };
}
return task;
});
setTasks(mergedTasks);
})
.catch((err) => console.error("Error fetching tasks:", err));
}, []);
useEffect(() => {
localStorage.setItem("taskEdits", JSON.stringify(taskEdits));
}, [taskEdits]);
0
The loss of data maybe due to the fact, that the state
is being reset on refresh. On mount
your useEffect
then runs and sets your localStorage
values to the now empty state.
Maybe you can try chaning your state logic:
const [taskEdits, setTaskEdits] = useState(() => {
return JSON.parse(localStorage.getItem("taskEdits")) || {};
});