Skip to content

Instantly share code, notes, and snippets.

@longdog
Created November 19, 2021 19:03
Show Gist options
  • Save longdog/aab331660652b397415b7ebae8b77a5d to your computer and use it in GitHub Desktop.
Save longdog/aab331660652b397415b7ebae8b77a5d to your computer and use it in GitHub Desktop.
react-router 6 and effector
import { createBrowserHistory } from "history";
export const browserHistory = createBrowserHistory();
import {
createEffect,
Event,
sample,
} from "effector";
import { browserHistory } from "lib/history";
export const redirectFx = createEffect((path: string) =>
browserHistory.push(path)
);
export function redirect(event: Event<any>, path: string) {
sample({
clock: event,
fn: () => path,
target: redirectFx,
});
}
import { Router } from "react-router-dom";
import React, { createElement, useLayoutEffect, useRef, useState } from "react";
import { browserHistory } from "lib/history";
import { BrowserHistory } from "history";
function BrowserRouter(_ref: any) {
let { basename, children } = _ref;
let historyRef = useRef<BrowserHistory>();
if (historyRef.current == null) {
historyRef.current = browserHistory;
}
let history = historyRef.current;
let [state, setState] = useState({
action: history!.action,
location: history!.location,
});
useLayoutEffect(() => history.listen(setState), [history]);
return createElement(Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history,
});
}
export const withRouter = (component: () => React.ReactNode) => () =>
(
<BrowserRouter>{component()}</BrowserRouter>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment