Skip to content

Commit

Permalink
Create ReactRouter7Adapter to use
Browse files Browse the repository at this point in the history
  • Loading branch information
Onitoxan committed Dec 9, 2024
1 parent eba9071 commit e063c20
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
44 changes: 44 additions & 0 deletions apps/hpc-ftsadmin/src/libs/useQueryParams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useContext } from 'react';
import {
useNavigate,
useLocation,
UNSAFE_DataRouterContext,
UNSAFE_LocationContext,
} from 'react-router';
import { type QueryParamAdapter, type PartialLocation } from 'use-query-params';

export const ReactRouter7Adapter = ({
children,
}: {
children: (adapter: QueryParamAdapter) => React.ReactElement | null;
}) => {
// we need the navigator directly so we can access the current version
// of location in case of multiple updates within a render (e.g. #233)
// but we will limit our usage of it and have a backup to just use
// useLocation() output in case of some kind of breaking change we miss.
// see: https://github.com/remix-run/react-router/blob/f3d87dcc91fbd6fd646064b88b4be52c15114603/packages/react-router-dom/index.tsx#L113-L131
const { location: unsafeLocation } = useContext(UNSAFE_LocationContext);
const navigate = useNavigate();
const router = useContext(UNSAFE_DataRouterContext)?.router;
const location = useLocation();

const adapter: QueryParamAdapter = {
replace(location2: PartialLocation) {
navigate(location2.search || '?', {
replace: true,
state: location2.state,
});
},
push(location2: PartialLocation) {
navigate(location2.search || '?', {
replace: false,
state: location2.state,
});
},
get location() {
return router?.state?.location ?? unsafeLocation ?? location;
},
};

return children(adapter);
};
4 changes: 2 additions & 2 deletions apps/hpc-ftsadmin/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import PageOrganization from './app/pages/organizations/organization';

import { RouteParamsValidator } from './app/components/route-params-validator';
import { QueryParamProvider } from 'use-query-params';
import { ReactRouter6Adapter } from 'use-query-params/adapters/react-router-6';
import { ReactRouter7Adapter } from './libs/useQueryParams';

const rootElement = document.getElementById('root');
if (!rootElement) {
Expand All @@ -26,7 +26,7 @@ const router = createBrowserRouter([
{
path: paths.home(),
element: (
<QueryParamProvider adapter={ReactRouter6Adapter}>
<QueryParamProvider adapter={ReactRouter7Adapter}>
<App />
</QueryParamProvider>
),
Expand Down

0 comments on commit e063c20

Please sign in to comment.