Skip to content

Instantly share code, notes, and snippets.

@nikakoy131
Last active September 18, 2020 17:51
Show Gist options
  • Save nikakoy131/09cbbaa2563871ff2d2955c7681a3727 to your computer and use it in GitHub Desktop.
Save nikakoy131/09cbbaa2563871ff2d2955c7681a3727 to your computer and use it in GitHub Desktop.
Temporary solutions for React Router 6 (https://github.com/ReactTraining/react-router/tree/v6.0.0-beta.0) for support router navigation from redux-saga. Usage example https://github.com/supasate/connected-react-router/issues/397#issuecomment-663521563
import React, { useReducer } from 'react';
import { BrowserHistory, Update, History } from 'history';
import { Router } from 'react-router-dom';
import {
Middleware, createSlice,
} from '@reduxjs/toolkit';
type ReduxAction<T = any> = {
type: string,
payload?: T,
};
const { reducer: routerReducer, actions: routerActions } = createSlice({
name: 'router',
initialState: {
path: window.location.pathname,
},
reducers: {
push: (state, action) => ({ path: action.payload }),
},
});
export const routerMiddleware = (history: BrowserHistory): Middleware => () => (
next,
) => (action: ReduxAction) => {
switch (action.type) {
case routerActions.push.type: {
history.push(action.payload);
return next(action);
}
default:
return next(action);
}
};
export interface BrowserRouterProps {
children?: React.ReactNode;
window?: Window;
history: History;
}
export function BrowserRouter({ children, history }: BrowserRouterProps) {
// const historyRef = React.useRef<BrowserHistory>();
// if (historyRef.current == null) {
// historyRef.current = createBrowserHistory({ window });
// }
// const history = historyRef.current;
const [state, dispatch] = useReducer((_: Update, action: Update) => action, {
action: history.action,
location: history.location,
});
React.useLayoutEffect(() => history.listen(dispatch), [history]);
return (
<Router
action={state.action}
location={state.location}
navigator={history}
>
{children}
</Router>
);
}
export { routerReducer, routerActions };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment