Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read same state from store for multiple times #155

Open
lomchik opened this issue May 8, 2020 · 2 comments
Open

Read same state from store for multiple times #155

lomchik opened this issue May 8, 2020 · 2 comments

Comments

@lomchik
Copy link

lomchik commented May 8, 2020

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() {}
}
@marcjulian
Copy link
Collaborator

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

@lomchik
Copy link
Author

lomchik commented May 8, 2020

Maybe one day when I will have less work (

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants