I'm building a web app that has a stopwatch feature, I developed it properly but did not store data(local storage). So, when the user re-loads and closes it, it will start from 0.
I want to keep this time data in "local storage" so that it will not start from 0 when the user closes or re-loads the website.
I keep these stopwatch functionalities in useStopwatch hook.
"use client";
import { useState } from "react";
export default function useStopwatch() {
const [days, setDays] = useState(0);
const [hrs, setHrs] = useState(0);
const [mins, setMins] = useState(0);
const [secs, setSecs] = useState(0);
const [progressTime, setProgressTime] = useState(0);
const [intervalId, setIntervalId] = useState<NodeJS.Timeout | undefined>();
let startTime = 0;
let elapsedTime = 0;
const start = () => {
startTime = Date.now() - elapsedTime;
const id = setInterval(updateTime, 1000);
setIntervalId(id);
};
const restart = () => {
clearInterval(intervalId);
setDays(0);
setHrs(0);
setMins(0);
setSecs(0);
startTime = 0;
elapsedTime = 0;
start();
};
const updateTime = () => {
elapsedTime = Date.now() - startTime;
const secs = Math.floor((elapsedTime / 1000) % 60);
const mins = Math.floor((elapsedTime / (1000 * 60)) % 60);
const hrs = Math.floor((elapsedTime / (1000 * 60 * 60)) % 60);
const days = Math.floor(elapsedTime / (1000 * 60 * 60 * 24));
setDays(days);
setHrs(hrs);
setMins(mins);
setSecs(secs);
setProgressTime(elapsedTime);
};
return { days, hrs, mins, secs, progressTime, start, restart };
}
Same code in GitHub repo: https://github.com/rakibul-wdp/quit-zina/blob/main/hooks/useStopwatch.ts
Full project code: https://github.com/rakibul-wdp/quit-zina
How can I implement this "localstorage" feature for this stopwatch?
You can achieve using this one.