Refactor useDarkStore in darkStore.tsx

This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-03-28 16:55:08 -03:00
commit ec46a56288

View file

@ -4,7 +4,7 @@ import { DarkStoreType } from "../types/zustand/dark";
const startedStars = Number(window.localStorage.getItem("githubStars")) ?? 0; const startedStars = Number(window.localStorage.getItem("githubStars")) ?? 0;
export const useDarkStore = create<DarkStoreType>((set) => ({ export const useDarkStore = create<DarkStoreType>((set, get) => ({
dark: JSON.parse(window.localStorage.getItem("isDark")!) ?? false, dark: JSON.parse(window.localStorage.getItem("isDark")!) ?? false,
stars: startedStars, stars: startedStars,
version: "", version: "",
@ -15,14 +15,23 @@ export const useDarkStore = create<DarkStoreType>((set) => ({
}); });
}, },
refreshStars: () => { refreshStars: () => {
if (window.localStorage.getItem("githubStars") !== null) { let lastUpdated = window.localStorage.getItem("githubStarsLastUpdated");
set(() => ({ stars: startedStars })); let diff = 0;
return; // check if lastUpdated actually exists
if (lastUpdated !== null) {
diff = Math.abs(new Date().getTime() - new Date(lastUpdated).getTime());
} }
getRepoStars("logspace-ai", "langflow").then((res) => { // if lastUpdated is null or the difference is greater than 2 hours
window.localStorage.setItem("githubStars", res.toString()); if (lastUpdated === null || diff > 7200000) {
set(() => ({ stars: res })); getRepoStars("logspace-ai", "langflow").then((res) => {
}); window.localStorage.setItem("githubStars", res.toString());
window.localStorage.setItem(
"githubStarsLastUpdated",
new Date().toString()
);
set(() => ({ stars: res, lastUpdated: new Date() }));
});
}
}, },
})); }));