Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 0 additions & 24 deletions vær/.gitignore

This file was deleted.

40 changes: 40 additions & 0 deletions vær/src/hooks/useStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useState, useEffect, useCallback } from "react";
import { getData, saveData } from "../services/storage";
import type {AppStorage} from "../services/storage";

export function useAppStorage() {

const [storage, setStorage] = useState<AppStorage>(getData);

const updateStorage = useCallback((updater: Partial<AppStorage> | ((prev: AppStorage) => AppStorage)) => {
setStorage((prev) => {
const nextState = typeof updater === "function" ? updater(prev) : { ...prev, ...updater };
saveData(nextState);
return nextState;
});
}, []);

// Star / unstar a location easily
const toggleStarredLocation = useCallback((locationId: string) => {
updateStorage((prev) => {
const exists = prev.starredLocations.includes(locationId);
const starredLocations = exists
? prev.starredLocations.filter((id) => id !== locationId)
: [...prev.starredLocations, locationId];

return { ...prev, starredLocations };
});
}, [updateStorage]);

// Update last visited page
const setLastPage = useCallback((lastPage: string) => {
updateStorage({ lastPage });
}, [updateStorage]);

return {
storage,
updateStorage,
toggleStarredLocation,
setLastPage,
};
}
48 changes: 48 additions & 0 deletions vær/src/services/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const STORAGE_KEY = "vær:storage_key"
const STORAGE_VERSION = 1;

//Type for tilstand
export interface AppStorage{
version: number;
starredLocations: string[]
lastPage: string;
}

const DEFAULT_STATE: AppStorage = {
version: STORAGE_VERSION,
starredLocations: [],
lastPage: "home",
};

export function getData(): AppStorage{
try{
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return DEFAULT_STATE;

const parsed = JSON.parse(raw) as AppStorage;

if (parsed.version !== STORAGE_VERSION) return DEFAULT_STATE;

return {...DEFAULT_STATE, ...parsed};
}
catch (err){
console.error("Failed to load store data");
return DEFAULT_STATE;
}
}

export function saveData(state: AppStorage): void{
try{
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));

}catch(err){
console.error("Failed saving", err);
}
}

// export function updateAppStorage(patch: Partial<AppStorage>): AppStorage {
// const current = getData();
// const updated = { ...current, ...patch };
// saveData(updated);
// return updated;
// }