Skip to content

Commit

Permalink
Add useShallowRouter hook
Browse files Browse the repository at this point in the history
  • Loading branch information
simon-debruijn committed Nov 21, 2024
1 parent a24909a commit 580450f
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/hooks/useShallowRouter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useRouter } from 'next/router';
import { useMemo } from 'react';

export const useShallowRouter = () => {
const router = useRouter();

return useMemo(() => {
const pushSearchParams = async (params: Record<string, string>) => {
const newQuery = {
...router.query,
};

Object.entries(params).forEach(([key, value]) => {
if (value !== '' && value !== undefined) {
newQuery[key] = value;
return;
}

if (key in newQuery) {
delete newQuery[key];
}
});

await router.push(
{
pathname: router.pathname,
query: newQuery,
},
undefined,
{
shallow: true,
},
);
};

return {
pushSearchParams,
};
}, [router]);
};

0 comments on commit 580450f

Please sign in to comment.