Skip to content

Instantly share code, notes, and snippets.

@dlindenkreuz
Last active September 15, 2017 13:55
Show Gist options
  • Save dlindenkreuz/2fc306f31ec0e404f0655d3d858d32a6 to your computer and use it in GitHub Desktop.
Save dlindenkreuz/2fc306f31ec0e404f0655d3d858d32a6 to your computer and use it in GitHub Desktop.
Composing redux-first-router thunks like koa middleware
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 })
}
// 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]),
},
}
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