Signals introduced new possibilities for Angular developers, personally I've been using a lot and exploring these possibilities, one of them is the straightforward way to sync data with localStorage (or sessionStorage).
It is amazing because sometimes we want to save the progress of some form or data in the browser, so lets see how to do it.
Create some interfaces
These interfaces are only there to define the shape of the state.
export interface Item {
id: string;
name: string;
}
export interface StateInterface {
items: Item[] | null;
}
Create a new service
@Injectable({
providedIn: 'root',
})
export class StateService {
state = signal<StateInterface>(
JSON.parse(localStorage.getItem('todo-data')!) as StateInterface
);
syncStorage = effect(() => {
localStorage.setItem('todo-data', JSON.stringify(this.state()));
});
}
Yes, its only it! Always the signals receive a modification, your localStorage will update! Amazing!
Demo
https://stackblitz.com/edit/stackblitz-starters-xa5w9r?file=src%2Fmain.ts
Top comments (0)