Last active
September 15, 2017 13:55
-
-
Save dlindenkreuz/2fc306f31ec0e404f0655d3d858d32a6 to your computer and use it in GitHub Desktop.
Composing redux-first-router thunks like koa middleware
This file contains 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 { RouteThunk } from "redux-first-router" | |
import * as compose from "koa-compose" | |
import { Middleware } from "koa-compose" | |
import { Dispatch } from "redux" | |
interface ThunkContext<S> { | |
dispatch: Dispatch<S> | |
getState: () => S | |
} | |
export type ThunkMiddleware<S = any> = Middleware<ThunkContext<S>> | |
export function composeThunk<S>( | |
thunks: Array<ThunkMiddleware<S>>, | |
): RouteThunk { | |
const composed = compose(thunks) | |
return (dispatch, getState) => composed({ dispatch, getState: getState as any }) | |
} |
This file contains 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
// redux-first-router routes map | |
import { composeThunk } from "./composeThunk.ts" | |
import { dataThunk, redirectToViewModeThunk } from "./thunks.ts" | |
export const routesMap: RoutesMap = { | |
ENTRYPOINT: { | |
path: "/:slug", | |
thunk: composeThunk([dataThunk, redirectToViewModeThunk]), | |
}, | |
TARGET: { | |
path: "/:slug/:viewMode", | |
thunk: composeThunk([dataThunk]), | |
}, | |
} |
This file contains 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
export const dataThunk: ThunkMiddleware = async ( | |
{ dispatch, getState }, | |
next, | |
) => { | |
const { slug } = (getState() as IRootReducerState).location | |
.payload as any | |
const res = await api.getBySlug(slug) | |
res.data.map(data => { | |
dispatch(FOUND(data.obj)) | |
}) | |
return next() | |
} | |
export const redirectToViewModeThunk: ThunkMiddleware<IRootReducerState> = async ({ | |
dispatch, | |
getState, | |
}) => { | |
const { slug } = (getState() as IRootReducerState).location | |
.payload as any | |
const { viewMode } = getState().obj | |
dispatch( | |
redirect( | |
{ | |
type: "TARGET", | |
payload: { slug, viewMode }, | |
} as any, | |
), | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment