Skip to content

Instantly share code, notes, and snippets.

@davidtranjs
Last active February 21, 2024 04:35
Show Gist options
  • Save davidtranjs/50517e523609116d07b39561dbacabb1 to your computer and use it in GitHub Desktop.
Save davidtranjs/50517e523609116d07b39561dbacabb1 to your computer and use it in GitHub Desktop.
React hook for Nextjs to update URL query without touching other existing queries
const useQuery = () => {
const router = useRouter();
const updateQuery = ({
query,
shallow,
scroll,
}: {
query: Record<string, string | number>;
shallow?: boolean;
scroll?: boolean;
}) => {
void router.push(
{
pathname: router.pathname,
query: {
...router.query,
...query,
},
},
{},
{
shallow,
scroll,
}
);
};
const removeQuery = ({
query,
shallow,
scroll,
}: {
query: string[];
shallow?: boolean;
scroll?: boolean;
}) => {
const newQuery = { ...router.query };
query.forEach((key) => {
delete newQuery[key];
});
void router.push(
{
pathname: router.pathname,
query: newQuery,
},
{},
{
shallow,
scroll,
}
);
};
return {
updateQuery,
removeQuery,
};
};
// usage
const { updateQuery, removeQuery } = useQuery();
// when you need to update url query without touch other existing queries
updateQuery({
query: {
tab: tab.value,
},
shallow: true,
});
// when you need to remove url query without touch other existing queries
removeQuery({
query: ["reportId"],
shallow: true,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment