Created
February 6, 2026 11:04
-
-
Save jdboachie/ef720006869b31dc61b6d7318957cb10 to your computer and use it in GitHub Desktop.
syncs a given writable signal to local storage (angular)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Injectable, Signal, WritableSignal, effect } from '@angular/core'; | |
| @Injectable({ | |
| providedIn: 'root', | |
| }) | |
| export class LocalSync { | |
| init<T>(storageKey: string, target: WritableSignal<T>): LocalSync { | |
| const raw = localStorage.getItem(storageKey); | |
| if (!raw) { | |
| return this; | |
| } | |
| try { | |
| const parsed = JSON.parse(raw) as T; | |
| target.set(parsed); | |
| } catch { | |
| // If parsing fails, keep current cart state | |
| } | |
| return this; | |
| } | |
| sync<T>(storageKey: string, cart: Signal<T>): void { | |
| effect(() => { | |
| const value = cart(); | |
| localStorage.setItem(storageKey, JSON.stringify(value)); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment