forked from ctrlplusb/easy-peasy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.d.ts
1065 lines (947 loc) · 25.1 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Component } from 'react';
import {
AnyAction,
compose,
Dispatch as ReduxDispatch,
Middleware,
Observable,
Reducer as ReduxReducer,
Store as ReduxStore,
StoreEnhancer,
} from 'redux';
import { O } from 'ts-toolbelt';
export type ReduxAction = AnyAction;
/**
* Picks only the keys of a certain type
*/
type KeysOfType<A extends object, B> = {
[K in keyof A]-?: A[K] extends B ? K : never;
}[keyof A];
/**
* This allows you to narrow keys of an object type that are index signature
* based.
*
* Based on answer from here:
* https://stackoverflow.com/questions/56422807/narrowing-a-type-to-its-properties-that-are-index-signatures/56423972#56423972
*/
type IndexSignatureKeysOfType<A extends Object> = {
[K in keyof A]: A[K] extends { [key: string]: any } | { [key: number]: any }
? string extends keyof A[K]
? K
: number extends keyof A[K]
? K
: never
: never;
}[keyof A];
type InvalidObjectTypes = string | Array<any> | RegExp | Date | Function;
type IncludesDeep3<Obj extends object, M extends any> = O.Includes<
Obj,
M
> extends 1
? 1
: O.Includes<
{
[P in keyof Obj]: Obj[P] extends object ? O.Includes<Obj, M> : 0;
},
1
>;
type IncludesDeep2<Obj extends object, M extends any> = O.Includes<
Obj,
M
> extends 1
? 1
: O.Includes<
{
[P in keyof Obj]: Obj[P] extends object ? IncludesDeep3<Obj[P], M> : 0;
},
1
>;
type IncludesDeep<Obj extends object, M extends any> = O.Includes<
Obj,
M
> extends 1
? 1
: O.Includes<
{
[P in keyof Obj]: Obj[P] extends object ? IncludesDeep2<Obj[P], M> : 0;
},
1
>;
type StateResolver<
Model extends object,
StoreModel extends object,
Result = any,
> = (state: State<Model>, storeState: State<StoreModel>) => Result;
type StateResolvers<Model extends object, StoreModel extends object> =
| []
| Array<StateResolver<Model, StoreModel, any>>;
type AnyFunction = (...args: any[]) => any;
type ActionEmitterTypes = Action<any, any> | Thunk<any, any, any, any, any>;
type ActionListenerTypes = ActionOn<any, any> | ThunkOn<any, any, any>;
type ActionTypes =
| ActionEmitterTypes
| ActionListenerTypes
| Unstable_EffectOn<any, any, any>;
interface ActionCreator<Payload = void> {
(payload: Payload): void;
type: string;
z__creator: 'actionWithPayload';
}
interface ThunkCreator<Payload = void, Result = any> {
(payload: Payload extends undefined ? void : Payload): Result;
type: string;
startType: string;
successType: string;
failType: string;
z__creator: 'thunkWithPayload';
}
type ActionOrThunkCreator<Payload = void, Result = void> =
| ActionCreator<Payload>
| ThunkCreator<Payload, Result>;
type Helpers<Model extends object, StoreModel extends object, Injections> = {
dispatch: Dispatch<StoreModel>;
fail: AnyFunction;
getState: () => State<Model>;
getStoreActions: () => Actions<StoreModel>;
getStoreState: () => State<StoreModel>;
injections: Injections;
meta: Meta;
};
// #region Helpers
/**
* This utility will pull the state within an action out of the Proxy form into
* a natural form, allowing you to console.log or inspect it.
*
* @param state - The action state
*
* @example
*
* ```typescript
* import { debug, action } from 'easy-peasy';
*
* const model = {
* todos: [],
* addTodo: action((state, payload) => {
* console.log(debug(state));
* state.todos.push(payload);
* console.log(debug(state));
* })
* }
* ```
*/
export function debug<StateDraft extends object = {}>(
state: StateDraft,
): StateDraft;
// #endregion
// #region Listeners
type ValidListenerProperties<ActionsModel extends object> = {
[P in keyof ActionsModel]: P extends IndexSignatureKeysOfType<ActionsModel>
? never
: ActionsModel[P] extends ActionListenerTypes
? P
: ActionsModel[P] extends object
? IncludesDeep<ActionsModel[P], ActionListenerTypes> extends 1
? P
: never
: never;
}[keyof ActionsModel];
type ListenerMapper<
ActionsModel extends object,
K extends keyof ActionsModel,
> = {
[P in K]: ActionsModel[P] extends ActionOn<any, any>
? ActionCreator<TargetPayload<any>>
: ActionsModel[P] extends ThunkOn<any, any, any>
? ThunkCreator<TargetPayload<any>, any>
: ActionsModel[P] extends object
? RecursiveListeners<ActionsModel[P]>
: ActionsModel[P];
};
type RecursiveListeners<ActionsModel extends object> = ListenerMapper<
ActionsModel,
ValidListenerProperties<ActionsModel>
>;
/**
* Filters a model into a type that represents the listener actions/thunks
*
* @example
*
* type OnlyListeners = Listeners<Model>;
*/
export type Listeners<Model extends object = {}> = RecursiveListeners<Model>;
// #endregion
// #region Actions
type ValidActionProperties<ActionsModel extends object> = {
[P in keyof ActionsModel]: P extends IndexSignatureKeysOfType<ActionsModel>
? never
: ActionsModel[P] extends ActionEmitterTypes
? P
: ActionsModel[P] extends object
? IncludesDeep<ActionsModel[P], ActionEmitterTypes> extends 1
? P
: never
: never;
}[keyof ActionsModel];
type ActionMapper<ActionsModel extends object, K extends keyof ActionsModel> = {
[P in K]: ActionsModel[P] extends Action<any, any>
? ActionCreator<ActionsModel[P]['payload']>
: ActionsModel[P] extends Thunk<any, any, any, any, any>
? ActionsModel[P]['payload'] extends void
? ThunkCreator<void, ActionsModel[P]['result']>
: ThunkCreator<ActionsModel[P]['payload'], ActionsModel[P]['result']>
: ActionsModel[P] extends object
? RecursiveActions<ActionsModel[P]>
: ActionsModel[P];
};
type RecursiveActions<ActionsModel extends object> = ActionMapper<
ActionsModel,
ValidActionProperties<ActionsModel>
>;
/**
* Filters a model into a type that represents the action/thunk creators.
*
* @example
*
* ```typescript
* import { Actions, useStoreActions } from 'easy-peasy';
* import { StoreModel } from './my-store';
*
* function MyComponent() {
* const doSomething = useStoreActions(
* (actions: Actions<StoreModel>) => actions.doSomething
* );
* }
* ```
*/
export type Actions<Model extends object = {}> = RecursiveActions<Model>;
// #endregion
// #region State
type StateTypes = Computed<any, any, any> | Reducer<any, any> | ActionTypes;
type StateMapper<StateModel extends object> = {
[P in keyof StateModel]: StateModel[P] extends Generic<infer T>
? T
: P extends IndexSignatureKeysOfType<StateModel>
? StateModel[P]
: StateModel[P] extends Computed<any, any, any>
? StateModel[P]['result']
: StateModel[P] extends Reducer<any, any>
? StateModel[P]['result']
: StateModel[P] extends object
? StateModel[P] extends InvalidObjectTypes
? StateModel[P]
: IncludesDeep<StateModel[P], StateTypes | ActionTypes> extends 1
? RecursiveState<StateModel[P]>
: StateModel[P]
: StateModel[P];
};
type FilterActionTypes<Model extends object> = {
[K in keyof Model as Model[K] extends ActionTypes ? never : K]: Model[K];
};
type RecursiveState<Model extends object> = StateMapper<
FilterActionTypes<Model>
>;
/**
* Filters a model into a type that represents the state only (i.e. no actions)
*
* @example
*
* ```typescript
* import { State, useStoreState } from 'easy-peasy';
* import { StoreModel } from './my-store';
*
* function MyComponent() {
* const stuff = useStoreState((state: State<StoreModel>) => state.stuff);
* }
* ```
*/
export type State<Model extends object = {}> = RecursiveState<Model>;
// #endregion
// #region Store + Config + Creation
/**
* Creates a store.
*
* https://easy-peasy.dev/docs/api/create-store.html
*
* @example
*
* ```typescript
* import { createStore } from 'easy-peasy';
*
* interface StoreModel {
* todos: string[];
* }
*
* const store = createStore<StoreModel>({
* todos: []
* });
* ```
*/
export function createStore<
StoreModel extends object = {},
InitialState extends undefined | object = undefined,
Injections extends object = {},
>(
model: StoreModel,
config?: EasyPeasyConfig<InitialState, Injections>,
): Store<StoreModel, EasyPeasyConfig<InitialState, Injections>>;
/**
* Configuration interface for stores.
*
* @example
*
* ```typescript
* import { createStore } from 'easy-peasy';
* import model from './my-model';
*
* const store = createStore(model, {
* devTools: false,
* name: 'MyConfiguredStore',
* });
* ```
*/
export interface EasyPeasyConfig<
InitialState extends undefined | object = undefined,
Injections extends object = {},
> {
compose?: typeof compose;
devTools?: boolean | object;
disableImmer?: boolean;
enhancers?: StoreEnhancer[];
initialState?: InitialState;
injections?: Injections;
middleware?: Array<Middleware<any, any, any>>;
mockActions?: boolean;
name?: string;
version?: number;
reducerEnhancer?: (reducer: ReduxReducer<any, any>) => ReduxReducer<any, any>;
}
export interface MockedAction {
type: string;
[key: string]: any;
}
export interface AddModelResult {
resolveRehydration: () => Promise<void>;
}
/**
* An Easy Peasy store. This is essentially a Redux store with additional enhanced
* APIs attached.
*
* @example
*
* ```typescript
* import { Store } from 'easy-peasy';
* import { StoreModel } from './store';
*
* type MyEasyPeasyStore = Store<StoreModel>;
* ```
*/
export interface Store<
StoreModel extends object = {},
StoreConfig extends EasyPeasyConfig<any, any> = EasyPeasyConfig<
undefined,
{}
>,
> extends ReduxStore<State<StoreModel>> {
addModel: <ModelSlice extends object>(
key: string,
modelSlice: ModelSlice,
) => AddModelResult;
clearMockedActions: () => void;
dispatch: Dispatch<StoreModel>;
getActions: () => Actions<StoreModel>;
getListeners: () => Listeners<StoreModel>;
getMockedActions: () => MockedAction[];
persist: {
clear: () => Promise<void>;
flush: () => Promise<void>;
resolveRehydration: () => Promise<void>;
};
reconfigure: <NewStoreModel extends object>(model: NewStoreModel) => void;
removeModel: (key: string) => void;
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/tc39/proposal-observable
*/
[Symbol.observable](): Observable<State<StoreModel>>;
}
// #endregion
// #region Dispatch
/**
* Enhanced version of the Redux Dispatch with action creators bound to it
*
* @example
*
* import { Dispatch } from 'easy-peasy';
* import { StoreModel } from './store';
*
* type DispatchWithActions = Dispatch<StoreModel>;
*/
export type Dispatch<
StoreModel extends object = {},
Action extends ReduxAction = AnyAction,
> = Actions<StoreModel> & ReduxDispatch<Action>;
// #endregion
// #region Types shared by ActionOn and ThunkOn
type Target = ActionOrThunkCreator<any> | string;
type TargetResolver<Model extends object, StoreModel extends object> = (
actions: Actions<Model>,
storeActions: Actions<StoreModel>,
) => Target | Array<Target>;
interface TargetPayload<Payload> {
type: string;
payload: Payload;
result?: any;
error?: Error;
resolvedTargets: Array<string>;
}
type PayloadFromResolver<
Resolver extends TargetResolver<any, any>,
Resolved = ReturnType<Resolver>,
> = Resolved extends string
? any
: Resolved extends ActionOrThunkCreator<infer Payload>
? Payload
: Resolved extends Array<infer T>
? T extends string
? any
: T extends ActionOrThunkCreator<infer Payload>
? Payload
: T
: unknown;
// #endregion
// #region Thunk
type Meta = {
path: string[];
parent: string[];
};
/**
* Declares a thunk against your model type definition.
*
* https://easy-peasy.dev/docs/typescript-api/thunk.html
*
* @param Model - The model that the thunk is being bound to.
* @param Payload - The type of the payload expected. Set to undefined if none.
* @param Injections - The type for the injections provided to the store
* @param StoreModel - The root model type for the store. Useful if using getStoreState helper.
* @param Result - The type for the expected return from the thunk.
*
* @example
*
* import { Thunk } from 'easy-peasy';
*
* interface TodosModel {
* todos: Array<string>;
* addTodo: Thunk<TodosModel, string>;
* }
*/
export interface Thunk<
Model extends object,
Payload = undefined,
Injections = any,
StoreModel extends object = {},
Result = any,
> {
type: 'thunk';
payload: Payload;
result: Result;
}
/**
* Declares an thunk against your model.
*
* Thunks are typically used to encapsulate side effects and are able to
* dispatch other actions.
*
* https://easy-peasy.dev/docs/api/thunk.html
*
* @example
*
* ```typescript
* import { thunk } from 'easy-peasy';
*
* const store = createStore({
* login: thunk(async (actions, payload) => {
* const user = await loginService(payload);
* actions.loginSucceeded(user);
* })
* });
* ```
*/
export function thunk<
Model extends object = {},
Payload = undefined,
Injections = any,
StoreModel extends object = {},
Result = any,
>(
thunk: (
actions: Actions<Model>,
payload: Payload,
helpers: Helpers<Model, StoreModel, Injections>,
) => Result,
): Thunk<Model, Payload, Injections, StoreModel, Result>;
// #endregion
// #region Listener Thunk
export interface ThunkOn<
Model extends object,
Injections = any,
StoreModel extends object = {},
> {
type: 'thunkOn';
}
export function thunkOn<
Model extends object = {},
Injections = any,
StoreModel extends object = {},
Resolver extends TargetResolver<Model, StoreModel> = TargetResolver<
Model,
StoreModel
>,
>(
targetResolver: Resolver,
handler: (
actions: Actions<Model>,
target: TargetPayload<PayloadFromResolver<Resolver>>,
helpers: Helpers<Model, StoreModel, Injections>,
) => any,
): ThunkOn<Model, Injections, StoreModel>;
// #endregion
// #region Action
/**
* Represents an action.
*
* @example
*
* import { Action } from 'easy-peasy';
*
* interface Model {
* todos: Array<Todo>;
* addTodo: Action<Model, Todo>;
* }
*/
export type Action<Model extends object, Payload = void> = {
type: 'action';
payload: Payload;
result: void | State<Model>;
};
/**
* @param {boolean} [immer=true] - If true, the action will be wrapped in an immer produce call. Otherwise, the action will update the state directly.
**/
interface Config {
immer?: boolean;
}
/**
* Declares an action.
*
* https://easy-peasy.dev/docs/api/action
*
* @example
*
* import { action } from 'easy-peasy';
*
* const store = createStore({
* count: 0,
* increment: action((state) => {
* state.count += 1;
* })
* });
*/
export function action<Model extends object = {}, Payload = any>(
action: (state: State<Model>, payload: Payload) => void | State<Model>,
config?: Config,
): Action<Model, Payload>;
// #endregion
// #region Listener Action
export interface ActionOn<
Model extends object = {},
StoreModel extends object = {},
> {
type: 'actionOn';
result: void | State<Model>;
}
export function actionOn<
Model extends object,
StoreModel extends object,
Resolver extends TargetResolver<Model, StoreModel>,
>(
targetResolver: Resolver,
handler: (
state: State<Model>,
target: TargetPayload<PayloadFromResolver<Resolver>>,
) => void | State<Model>,
config?: Config,
): ActionOn<Model, StoreModel>;
// #endregion
// #region Computed
/**
* Represents a computed property.
*
* @example
*
* import { Computed } from 'easy-peasy';
*
* interface Model {
* products: Array<Product>;
* totalPrice: Computed<Model, number>;
* }
*/
export interface Computed<
Model extends object,
Result,
StoreModel extends object = {},
> {
type: 'computed';
result: Result;
}
type DefaultComputationFunc<Model extends object, Result> = (
state: State<Model>,
) => Result;
type ExtractReturnTypes<T extends readonly ((...args: any[]) => any)[]> = [
...{
[K in keyof T]: T[K] extends (...args: any[]) => infer R ? R : never;
},
];
export function computed<
Model extends object = {},
Result = void,
StoreModel extends object = {},
Resolvers extends StateResolvers<Model, StoreModel> = StateResolvers<
Model,
StoreModel
>,
>(
resolversOrCompFunc: Resolvers | DefaultComputationFunc<Model, Result>,
compFunc?: (...args: ExtractReturnTypes<Resolvers>) => Result,
): Computed<Model, Result, StoreModel>;
// #endregion
// #region EffectOn
export interface Unstable_EffectOn<
Model extends object = {},
StoreModel extends object = {},
Injections = any,
> {
type: 'effectOn';
}
type Change<Resolvers extends StateResolvers<any, any>> = {
prev: ExtractReturnTypes<Resolvers>;
current: ExtractReturnTypes<Resolvers>;
action: {
type: string;
payload?: any;
};
};
export type Dispose = () => any;
export function unstable_effectOn<
Model extends object = {},
StoreModel extends object = {},
Injections = any,
Resolvers extends StateResolvers<Model, StoreModel> = StateResolvers<
Model,
StoreModel
>,
>(
dependencies: Resolvers,
effect: (
actions: Actions<Model>,
change: Change<Resolvers>,
helpers: Helpers<Model, StoreModel, Injections>,
) => undefined | void | Dispose,
): Unstable_EffectOn<Model, StoreModel, Injections>;
// #endregion
// #region Reducer
/**
* A reducer type.
*
* Useful when declaring your model.
*
* @example
*
* import { Reducer } from 'easy-peasy';
*
* interface Model {
* router: Reducer<ReactRouterState>;
* }
*/
export type Reducer<State = any, Action extends ReduxAction = AnyAction> = {
type: 'reducer';
result: State;
};
/**
* Allows you to declare a custom reducer to manage a bit of your state.
*
* https://github.com/ctrlplusb/easy-peasy#reducerfn
*
* @example
*
* import { reducer } from 'easy-peasy';
*
* const store = createStore({
* counter: reducer((state = 1, action) => {
* switch (action.type) {
* case 'INCREMENT': return state + 1;
* default: return state;
* }
* })
* });
*/
export function reducer<State>(
reducer: ReduxReducer<State>,
config?: Config,
): Reducer<State>;
// #endregion
// #region Generics
/**
* Used to declare generic state on a model.
*
* @example
*
* interface MyGenericModel<T> {
* value: Generic<T>;
* setValue: Action<MyGenericModel<T>, T>;
* }
*
* const numberModel: MyGenericModel<number> = {
* value: generic(1337),
* setValue: action((state, value) => {
* state.value = value;
* })
* };
*/
export class Generic<T> {
type: 'ezpz__generic';
}
/**
* Used to assign a generic state value against a model.
*
* @example
*
* interface MyGenericModel<T> {
* value: Generic<T>;
* setValue: Action<MyGenericModel<T>, T>;
* }
*
* const numberModel: MyGenericModel<number> = {
* value: generic(1337),
* setValue: action((state, value) => {
* state.value = value;
* })
* };
*/
export function generic<T>(value: T): Generic<T>;
// #endregion Generics
// #region Hooks
/**
* A React Hook allowing you to use state within your component.
*
* https://easy-peasy.dev/docs/api/use-store-state.html
*
* Note: you can create a pre-typed version of this hook via "createTypedHooks"
*
* @example
*
* import { useStoreState, State } from 'easy-peasy';
* import { StoreModel } from './store';
*
* function MyComponent() {
* const todos = useStoreState((state: State<StoreModel>) => state.todos.items);
* return todos.map(todo => <Todo todo={todo} />);
* }
*/
export function useStoreState<
StoreState extends State<any> = State<{}>,
Result = any,
>(
mapState: (state: StoreState) => Result,
equalityFn?: (prev: Result, next: Result) => boolean,
): Result;
/**
* A React Hook allowing you to use actions within your component.
*
* https://easy-peasy.dev/docs/api/use-store-actions.html
*
* Note: you can create a pre-typed version of this hook via "createTypedHooks"
*
* @example
*
* import { useStoreActions, Actions } from 'easy-peasy';
*
* function MyComponent() {
* const addTodo = useStoreActions((actions: Actions<StoreModel>) => actions.todos.add);
* return <AddTodoForm save={addTodo} />;
* }
*/
export function useStoreActions<
StoreActions extends Actions<any> = Actions<{}>,
Result = any,
>(mapActions: (actions: StoreActions) => Result): Result;
/**
* A react hook that returns the store instance.
*
* https://easy-peasy.dev/docs/api/use-store.html
*
* Note: you can create a pre-typed version of this hook via "createTypedHooks"
*
* @example
*
* import { useStore } from 'easy-peasy';
*
* function MyComponent() {
* const store = useStore();
* return <div>{store.getState().foo}</div>;
* }
*/
export function useStore<
StoreModel extends object = {},
StoreConfig extends EasyPeasyConfig<any, any> = EasyPeasyConfig<
undefined,
{}
>,
>(): Store<StoreModel, StoreConfig>;
/**
* A React Hook allowing you to use the store's dispatch within your component.
*
* https://easypeasy.now.sh/docs/api/use-store-dispatch.html
*
* Note: you can create a pre-typed version of this hook via "createTypedHooks"
*
* @example
*
* import { useStoreDispatch } from 'easy-peasy';
*
* function MyComponent() {
* const dispatch = useStoreDispatch();
* return <AddTodoForm save={(todo) => dispatch({ type: 'ADD_TODO', payload: todo })} />;
* }
*/
export function useStoreDispatch<
StoreModel extends object = {},
>(): Dispatch<StoreModel>;
/**
* A utility function used to create pre-typed hooks.
*
* https://easypeasy.now.sh/docs/api/create-typed-hooks.html
*
* @example
* import { StoreModel } from './store';
*
* const { useStoreActions, useStoreState, useStoreDispatch, useStore } = createTypedHooks<StoreModel>();
*
* useStoreActions(actions => actions.todo.add); // fully typed
*/
export function createTypedHooks<StoreModel extends object = {}>(): {
useStoreActions: <Result>(
mapActions: (actions: Actions<StoreModel>) => Result,
) => Result;
useStoreDispatch: () => Dispatch<StoreModel>;
useStoreState: <Result>(
mapState: (state: State<StoreModel>) => Result,
equalityFn?: (prev: Result, next: Result) => boolean,
) => Result;
useStore: () => Store<StoreModel>;
};
// #endregion
// #region StoreProvider
/**
* Exposes the store to your app (and hooks).
*
* https://easypeasy.now.sh/docs/api/store-provider.html
*
* @example
*
* import { StoreProvider } from 'easy-peasy';
* import store from './store';
*
* ReactDOM.render(
* <StoreProvider store={store}>
* <App />
* </StoreProvider>
* );
*/
export class StoreProvider<StoreModel extends object = {}> extends Component<{
store: Store<StoreModel>;
children?: React.ReactNode;
}> {}
// #endregion
// #region Context + Local Stores
interface StoreModelInitializer<
StoreModel extends object,
RuntimeModel extends undefined | object,
> {
(runtimeModel?: RuntimeModel): StoreModel;
}
export function createContextStore<
StoreModel extends object = {},
Injections extends object = {},
RuntimeModel extends undefined | object = StoreModel,
StoreConfig extends EasyPeasyConfig<any, any> = EasyPeasyConfig<
undefined,
Injections
>,
>(
model: StoreModel | StoreModelInitializer<StoreModel, RuntimeModel>,
config?: StoreConfig,
): {
Provider: React.FC<{
children?: React.ReactNode;
runtimeModel?: RuntimeModel;
injections?: Injections | ((previousInjections: Injections) => Injections);
}>;
useStore: () => Store<StoreModel, StoreConfig>;
useStoreState: <Result = any>(
mapState: (state: State<StoreModel>) => Result,
equalityFn?: (prev: Result, next: Result) => boolean,