angular-architects / ngrx-toolkit

Various Extensions for the NgRx Signal Store
MIT License
104 stars 17 forks source link

Feature storage sync #7

Closed bohoffi closed 4 months ago

bohoffi commented 6 months ago

PR was created at the suggestion of @rainerhahnekamp in ngrx/plattform#4180.

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

[ ] Bugfix
[x] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Build related changes
[ ] CI related changes
[ ] Documentation content changes
[ ] Other... Please describe:

What is the new behavior?

  1. Adding storage (localstorage/sessionstorage) synchronization to the store:
    const SyncStore = signalStore(
    withStorageSync('synced'),
    );
  2. Adding methods for manual synchronization
    
    const SyncStore = signalStore(
    withStorageSync('synced'),
    );

const syncStore = inject(SyncStore);

syncStore.clearStorage(); // clears the stores item in storage syncStore.readFromStorage(); // reads the stores item from storage and patches the state syncStore.writeToStorage(); // writes the current state to storage

3. Offering customization options
```ts
const SyncStore = signalStore(
  withStorageSync<User>({
    key: 'synced',
    autoSync: false, // read from storage on init and write on state changes - `true` by default
    select: (state: User) => Partial<User>, // projection to keep specific slices in sync
    parse: (stateString: string) => State, // custom parsing from storage - `JSON.parse` by default
    stringify: (state: User) => string, // custom stringification - `JSON.stringify` by default
    storage: () => sessionstorage, // factory to select storage to sync with
  }),
);

Does this PR introduce a breaking change?

[ ] Yes
[x] No
bohoffi commented 4 months ago

@rainerhahnekamp the build on main failed due to the bundle budget - should I open a new PR for increasing the budget?

rainerhahnekamp commented 4 months ago

Hi @bohoffi, first of all, thanks for your contribution. The build pipeline is not something I'd call stable at the moment. So, work is still in progress 😃

Every bit of improvement is more than welcomed.