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

Feature/stores #44

Merged
merged 9 commits into from
Sep 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 19 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 12 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cobuildlab/react-simple-state",
"version": "0.6.2",
"version": "0.7.0",
"description": "Simple and Lightweight state management for react applications. ",
"main": "lib/index.js",
"types": "./lib/index.d.ts",
Expand Down Expand Up @@ -39,15 +39,23 @@
"jest": "^26.0.1",
"lint-staged": "^10.2.2",
"prettier": "^2.0.5",
"react": "^16.13.1",
"react": "17.0.2",
"react-test-renderer": "^16.13.1",
"ts-jest": "^25.5.1",
"typedoc": "^0.17.8",
"typedoc-plugin-markdown": "^2.3.1",
"typescript": "^4.2.2"
"typescript": "^4.4.2"
},
"peerDependencies": {
"react": "^16.8.6"
"react": ">=16.13.1"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
}
},
"husky": {
"hooks": {
Expand Down
6 changes: 4 additions & 2 deletions src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ export function createAction<T, U extends any[], E = Error, R = unknown>(
try {
data = await action(...params);
} catch (error) {
errorEvent.dispatch(error);
return { error };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
errorEvent.dispatch(error as any);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { error } as { error: any };
}

event.dispatch(data);
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@ export * from './hooks';
export * from './views';
export * from './event';
export * from './actions';
export * from './store';
export * from './store-hooks';
export * from './store-utils';
6 changes: 3 additions & 3 deletions src/pub-sub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ export interface Subscription {
}

export interface Subscriber<T> {
update: (value: T | null) => void;
update: (value: T) => void;
}

export interface Publisher<T> {
subscribers: Subscriber<T>[];

subscribe(subscriber: Subscriber<T>): Subscription;

notify(value: T | null): void;
notify(value: T): void;
}

/**
Expand Down Expand Up @@ -53,7 +53,7 @@ class ConcretePublisher<T> implements Publisher<T> {
return new ConcreteSubscription(this, subscriber);
}

public notify(value: T | null): void {
public notify(value: T): void {
for (const subscriber of this.subscribers) {
subscriber.update(value);
}
Expand Down
88 changes: 88 additions & 0 deletions src/store-hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { useEffect, useRef, useState } from 'react';
import { Store } from './store';

/**
* @param {Store} store - Store to subscribe.
* @param {Function} callback - Function to call on each dipatch.
*/
export function useStoreSubcription<T>(
store: Store<T>,
callback: (data: T) => void,
): void {
const callbacksRef = useRef({
callback,
});

callbacksRef.current = {
callback,
};

useEffect(() => {
const unsubscribeSuccess = store.subscribe((data) => {
if (callbacksRef.current.callback) {
callbacksRef.current.callback(data);
}
});

return () => {
unsubscribeSuccess.unsubscribe();
};
}, [store]);
}

/**
* @param {Store} store - Store to subscribe.
* @param {Function} errorcCallback - Function to call on each error dipatch.
*/
export function useStoreErrorSubscription<T>(
store: Store<T>,
errorcCallback: (data: Error) => void,
): void {
const callbacksRef = useRef({
errorcCallback,
});

callbacksRef.current = {
errorcCallback,
};

useEffect(() => {
const unsubscribeError = store.subscribeError((data) => {
if (callbacksRef.current.errorcCallback) {
callbacksRef.current.errorcCallback(data);
}
});

return () => {
unsubscribeError.unsubscribe();
};
}, [store]);
}

/**
* @param {Store} store - Store to subscribe.
* @returns {Object} - Resulto object from the store.
*/
export function useStore<T>(store: Store<T>): T {
const [state, setState] = useState(store.get());

useStoreSubcription(store, (data) => {
setState(data);
});

return state;
}

/**
* @param {Store} store - Store to subscribe.
* @returns {Object} - Resulto object from the store.
*/
export function useStoreError<T>(store: Store<T>): Error | null {
const [state, setState] = useState<Error | null>(null);

useStoreErrorSubscription(store, (data) => {
setState(data as Error);
});

return state;
}
34 changes: 34 additions & 0 deletions src/store-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { CheckDispatchType, Store } from './store';

/**
* @param {Store} store - Event.
* @param {Function} callback - Callback.
* @param {Function} sideEffect - Callback.
* @returns {Function} Reducer fucntion.
*/
export function createStoreAction<T, V extends unknown[], U = unknown>(
store: Store<T, U>,
callback:
| ((prevState: T, ...params: V) => CheckDispatchType<T, U>)
| ((prevState: T, ...params: V) => Promise<CheckDispatchType<T, U>>),
sideEffect?: (...params: V) => void,
) {
return (...params: V): void => {
if (sideEffect) {
sideEffect(...params);
}
const result = callback(store.get(), ...params);

if (result instanceof Promise) {
result
.then((data) => {
store.dispatch(data);
})
.catch((e) => {
store.dispatchError(e);
});
return;
}
store.dispatch(result);
};
}
54 changes: 29 additions & 25 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,30 @@ import {
Subscriber,
Subscription,
} from './pub-sub';
import { Reducer } from './event';

export type EventParams<T, U extends []> = {
initialValue?: T | null;
reducer: Reducer<T, U>;
stores: [...U];
type Reducer<T, R> = (prevState: T, newState: R) => T;
export type CheckDispatchType<T, R> = R extends unknown ? T : R;

export type StoreParams<T, R> = {
initialValue: T;
reducer?: Reducer<T, R>;
};
export class Store<T, U extends []> {
private value: T | null = null;
private readonly reducer?: Reducer<T, [...U]>;
export class Store<T, R = unknown> {
private value: T;
private initialValue: T;
private publisher: Publisher<T> = new ConcretePublisher();
private errorPublisher: Publisher<Error> = new ConcretePublisher();
private reducer: Reducer<T, R> | undefined;

constructor(eventDescriptor: StoreParams<T, R>) {
this.value = eventDescriptor.initialValue;
this.initialValue = eventDescriptor.initialValue;

constructor(eventDescriptor?: EventParams<T, U>) {
if (eventDescriptor && eventDescriptor.initialValue)
this.value = eventDescriptor.initialValue;
this.reducer = eventDescriptor?.reducer;
this.reducer = eventDescriptor.reducer;
}

subscribe(
subscriber: (value: T | null) => void,
subscriber: (value: T) => void,
receiveLastValue = false,
): Subscription {
const _subscriber: Subscriber<T> = {
Expand All @@ -34,27 +37,28 @@ export class Store<T, U extends []> {
return this.publisher.subscribe(_subscriber);
}

subscribeError(subscriber: (value: Error | null) => void): Subscription {
subscribeError(subscriber: (value: Error) => void): Subscription {
const _subscriber: Subscriber<Error> = {
update: subscriber,
};
return this.errorPublisher.subscribe(_subscriber);
}

dispatch(eventValue: T | U | null): void {
const value = Object.freeze(
this.reducer !== null && this.reducer !== undefined
? this.reducer(eventValue as U)
: (eventValue as T),
);
dispatch(eventValue: CheckDispatchType<T, R>): void {
const value = this.reducer
? this.reducer(this.value, eventValue as R)
: this.value;

this.value = value;
this.publisher.notify(value);

this.publisher.notify(Object.freeze(value));
}

dispatchError(value: Error): void {
this.errorPublisher.notify(value);
}
get(): T | null {

get(): T {
return Object.freeze(this.value);
}

Expand All @@ -64,10 +68,10 @@ export class Store<T, U extends []> {
* @param {boolean} dispatch -
*/
clear(dispatch = false): void {
this.value = this.initialValue;

if (dispatch) {
this.dispatch(null); // Empty dispatch
} else {
this.value = null;
this.dispatch(this.value); // Empty dispatch
}
}
}