Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The essence of redux in 30 lines of code.
class Store<S> {
private readonly reducer: (state: S, action: Action) => S;
private state: S;
private listeners: Listener[] = [];
constructor(reducer, state) {
this.reducer = reducer;
this.state = state;
}
getState(): S {
return this.state;
}
dispatch(action: Action): void {
this.state = this.reducer(this.state, action);
this.listeners.forEach(it => it());
}
subscribe(listener: Listener): Unsubscribe {
this.listeners = [...this.listeners, listener];
return () => {
this.listeners = this.listeners.filter(it => it !== listener);
};
}
}
type Action = { type: string; payload: any };
type Listener = () => void;
type Unsubscribe = () => void;
@jordrake

This comment has been minimized.

Copy link

commented May 15, 2019

Your listeners should be provided this.state on line 17.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.