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

jordrake commented May 15, 2019

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

@deenem

This comment has been minimized.

Copy link

deenem commented Oct 18, 2019

Rather than having the reducer passed into the constructor, would it make sense to have a reducers array and an addReducer(s) and removeReducer(s) function?
It just seems unlikely that a complex system would only ever have one, fixed reducer function for the entire State. More likely that modules would want to add reducers to modify state when they are instantiated, then remove their reducers when they were done.

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.