Skip to content

Read same state from store for multiple times #155

@lomchik

Description

@lomchik

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() {}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions