async-storage-plugin icon indicating copy to clipboard operation
async-storage-plugin copied to clipboard

Read same state from store for multiple times

Open lomchik opened this issue 5 years ago • 2 comments

All states are read from storage on InitState and on UpdateState. This brings the app to the problem of inconsistent data when state was changed (in memory) but then overwritten from storage. To fix this I propose: on UpdateState get only addedStates from storage.

Also, it would be nice to:

  1. make sure that state was read once from storage
  2. allow writing state to storage only after data was read from storage.

I have added a test on this.

import { TestBed } from '@angular/core/testing';
import { NgxsAsyncStoragePluginModule } from '@ngxs-labs/async-storage-plugin';
import { NgxsModule, State, Store, UpdateState } from '@ngxs/store';

describe('read state from storage once', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        NgxsModule.forRoot([StateToStore]),
        NgxsAsyncStoragePluginModule.forRoot(KeyValueStorageMock, {
          key: [StateToStore.name]
        })
      ],
      providers: [KeyValueStorageMock]
    });
  });

  it(`does not get again ${StateToStore.name} when ${UpdateState.name} dispatched`, async () => {
    const store = TestBed.get(Store) as Store;
    // was get on InitState
    expect(getItemSpy).toHaveBeenCalledWith(StateToStore.name);
    getItemSpy.calls.reset();
    await store.dispatch(new UpdateState()).toPromise();
    expect(getItemSpy).not.toHaveBeenCalledWith(StateToStore.name);
  });
});

const getItemSpy = jasmine.createSpy('getItem');

class KeyValueStorageMock {
  getItem(key: string) {
    console.log(key);
    return getItemSpy(key);
  }
  setItem() {}
}

@State<string>({
  defaults: 'default',
  name: StateToStore.name
})
class StateToStore {
  constructor() {}
}

lomchik avatar May 08 '20 11:05 lomchik

@lomchik do you mind providing a PR for your suggestion?

marcjulian avatar May 08 '20 11:05 marcjulian

Maybe one day when I will have less work (

lomchik avatar May 08 '20 12:05 lomchik