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