Last active
February 19, 2017 09:31
-
-
Save danielearwicker/d10eb5c9b274728dd45f46bab0b0ebe3 to your computer and use it in GitHub Desktop.
Remox (Redux in MobX)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { autorun } from "mobx"; | |
import { createStore, Action, Reducer } from "./remox" | |
interface Person { firstName: string; lastName: string; } | |
interface SetFirstName { type: "SET_FIRST_NAME", newFirstName: string; } | |
interface SetLastName { type: "SET_LAST_NAME", newLastName: string; } | |
function personReducer(state:Person, action: SetFirstName | SetLastName) { | |
switch (action.type) { | |
case "SET_FIRST_NAME": | |
return { ...state, firstName: action.newFirstName }; | |
case "SET_LAST_NAME": | |
return { ...state, lastName: action.newLastName }; | |
} | |
return state; | |
} | |
const person = createStore({ firstName: "", lastName: "" }, personReducer); | |
const quit = autorun(() => console.log(person.getState())); | |
person.dispatch({ type: "SET_FIRST_NAME", newFirstName: "Homer" }); | |
person.dispatch({ type: "SET_LAST_NAME", newLastName: "Simpson" }); | |
quit(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { observable, runInAction } from "mobx"; | |
// An action has a string property called type | |
export interface Action<Type extends string> { readonly type: Type; } | |
// Reducer evolves state as instructed by an action | |
export type Reducer<State, Action> = (state: State, action: Action) => State; | |
export interface Store<State, Action> { | |
getState(): State; | |
dispatch(action: Action): void; | |
} | |
// Stores a State value and uses reducer that accepts Action (typically a union of Action<T> variants) | |
export function createStore<State, Action>(init: State, reducer: Reducer<State, Action>) { | |
const state = observable.shallowBox<State>(init); | |
return { | |
getState(): State { | |
return state.get(); | |
}, | |
dispatch(action: Action) { | |
runInAction(() => state.set(reducer(state.get(), action))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment