Skip to content

Instantly share code, notes, and snippets.

@dherges
Last active September 28, 2017 19:49
Show Gist options
  • Save dherges/144fb0898c37b6fdbae59ccff67c8b4b to your computer and use it in GitHub Desktop.
Save dherges/144fb0898c37b6fdbae59ccff67c8b4b to your computer and use it in GitHub Desktop.
Redux Lite for local states
/*
* Minimal redux for local states
* @link https://spin.atomicobject.com/2017/07/24/redux-action-pattern-typescript/
*/
export interface ReducerFn<S, A> {
(state: S, action: A): S
}
export interface Action<T> {
readonly type: any;
payload?: T;
}
export class StoreLite<S, A> {
private subject: Subject<S>;
constructor (
initialState: S,
private reducerFn: ReducerFn<S, A>
) {
this.subject = new BehaviorSubject(initialState);
}
public dispatch(action: A): void {
// TODO ... typed immutable record here ... initial state is there, S is there ... oculd be possible
this.subject.next(this.reducerFn(this.state, action));
}
public subscribe(/* ... */): Subscription {
return this.subject.asObservable().subscribe(/* ... */);
}
}
// --- user land
interface MyState {
count: number;
}
export const initialState: MyState = {
count: 100
};
export class FooAction implements Action<number> {
readonly type = "FOO";
constructor(
public payload: number
) {}
}
type ActionTypes = FooAction;
export const reducer: ReducerFn<MyState, ActionTypes> =
(state = initialState, action) => {
switch (action.type) {
case "FOO":
return { count: action.payload };
}
return state;
}
const localRedux: StoreLite<MyState, ActionTypes> = new StoreLite(
initialState,
reducer
);
localRedux.dispatch(new FooAction(123));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment