Skip to content

Instantly share code, notes, and snippets.

@joshcox
Created October 12, 2018 22:23
Show Gist options
  • Save joshcox/420852098c0decba29902a276adb0a03 to your computer and use it in GitHub Desktop.
Save joshcox/420852098c0decba29902a276adb0a03 to your computer and use it in GitHub Desktop.
import { applyMiddleware, createStore, Action, ActionCreator, Middleware, AnyAction } from "redux";
import thunkMiddleware, { ThunkAction, ThunkMiddleware, ThunkDispatch } from "redux-thunk";
interface IRootState {
derp: string;
}
const initialState: IRootState = {
derp: "fug"
};
type Actions = Action & { payload: string };
const RootReducer = (state: IRootState | undefined, action: Actions): IRootState => {
if (state === undefined) {
return undefined;
}
switch (action.type) {
case "DerpAction":
return ({ ...state, ...{ derp: action.payload }});
default:
return state;
}
}
const middleware = [thunkMiddleware];
// You need to tell applyMiddleware what the overloaded version of Dispatch is. It can't infer it. So here we say this
// is a ThunkDispatch over IRootState, no extra arguments, and any of our Actions.
const daStore2 = createStore(RootReducer, initialState, applyMiddleware<ThunkDispatch<IRootState, never, Actions>>(...middleware));
export const fugU: ActionCreator<ThunkAction<Promise<{ type: string; payload: string; }>, IRootState, void, Actions>> = (id: number) =>
(dispatch) => new Promise((res) => setTimeout(() => res("huh?"), 20))
.then((payload: string) => dispatch({ type: "DerpAction", payload }));
daStore2.dispatch(fugU(2));
@joshcox
Copy link
Author

joshcox commented Oct 12, 2018

What's more - createStore can infer everything else if you provide that Ext type to applyMiddleware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment