From 330ae2c1e24367bd951b2d82436cb4dd84263364 Mon Sep 17 00:00:00 2001 From: Boris Cherny Date: Sun, 22 Apr 2018 22:54:59 -0700 Subject: [PATCH] add getState API --- src/index.js.flow | 3 +++ src/index.ts | 7 +++++++ test/stateless.tsx | 28 ++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/src/index.js.flow b/src/index.js.flow index f873850..c429fca 100644 --- a/src/index.js.flow +++ b/src/index.js.flow @@ -16,6 +16,7 @@ export interface Store { onAll>(): Observable<$Values>>; before>(key: K): Observable<$ElementType>; beforeAll>(): Observable<$Values>>; + getState(): $ReadOnly; } declare export class StoreSnapshot implements Store { @@ -25,6 +26,7 @@ declare export class StoreSnapshot implements Store { onAll>(): Observable<$Values>>; before>(key: K): Observable<$ElementType>; beforeAll>(): Observable<$Values>>; + getState(): $ReadOnly; } declare export class StoreDefinition implements Store { @@ -34,6 +36,7 @@ declare export class StoreDefinition implements Store { onAll>(): Observable<$Values>>; before>(key: K): Observable<$ElementType>; beforeAll>(): Observable<$Values>>; + getState(): $ReadOnly; } declare export function createStore(initialState: Actions): StoreDefinition diff --git a/src/index.ts b/src/index.ts index 48d8e28..04c3945 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,7 @@ export interface Store { onAll(): RxJS.Observable[keyof Actions]> before(key: K): RxJS.Observable[K]> beforeAll(): RxJS.Observable[keyof Actions]> + getState(): Readonly } export class StoreSnapshot implements Store { @@ -41,6 +42,9 @@ export class StoreSnapshot implements Store { beforeAll() { return this.store.beforeAll() } + getState() { + return Object.freeze(Object.assign({}, this.state)) + } private assign( key: K, value: Actions[K]) { @@ -80,6 +84,9 @@ export class StoreDefinition implements Store { this.alls.emit(key, { key, previousValue, value }) } } + getState() { + return this.store.getState() + } } export function createStore( diff --git a/test/stateless.tsx b/test/stateless.tsx index 8ea64aa..ae085eb 100644 --- a/test/stateless.tsx +++ b/test/stateless.tsx @@ -168,3 +168,31 @@ test('[stateless] it should typecheck with additional props', t => { t.pass() }) + +test('#getState should return up to date state', t => { + let A = connect(store)(({ store }) => +
+ {store.get('isTrue') ? 'True' : 'False'} + +
+ ) + + withElement(A, _ => { + t.deepEqual(store.getState(), { isTrue: true, users: [] }) + Simulate.click(_.querySelector('button')!) + t.deepEqual(store.getState(), { isTrue: false, users: [] }) + Simulate.click(_.querySelector('button')!) + t.deepEqual(store.getState(), { isTrue: true, users: [] }) + Simulate.click(_.querySelector('button')!) + t.deepEqual(store.getState(), { isTrue: false, users: [] }) + }) +}) + +test('#getState should not be writeable', t => { + let A = connect(store)(({ store }) => +
+ ) + withElement(A, _ => + t.throws(() => (store.getState() as any).isTrue = false) + ) +})