Last active
February 21, 2024 04:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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