diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-12-01 19:34:58 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-12-04 19:00:04 +0100 |
| commit | 53b63ac27c2275262db9a04be02210a3287aa71d (patch) | |
| tree | 814968e10cad25e1b34ab251de42ac5ecb82b346 /src/utils/hooks/use-redirection/use-redirection.ts | |
| parent | 11e3ee75fcab0ab54b2bc1713a402c5cc3070c2d (diff) | |
refactor(pages): refine Blog pages
* replace usePostsList with useArticlesList to keep names coherent
* remove useIsMounted hook
* rewrite useRedirection hook
* add redirect in getStaticProps to avoid unecessary fetching
* move Pagination component in a noscript tag
* use hooks to refresh thematics and topics lists
* complete Cypress tests
Diffstat (limited to 'src/utils/hooks/use-redirection/use-redirection.ts')
| -rw-r--r-- | src/utils/hooks/use-redirection/use-redirection.ts | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/utils/hooks/use-redirection/use-redirection.ts b/src/utils/hooks/use-redirection/use-redirection.ts new file mode 100644 index 0000000..1592a33 --- /dev/null +++ b/src/utils/hooks/use-redirection/use-redirection.ts @@ -0,0 +1,41 @@ +import { useRouter } from 'next/router'; +import { useEffect } from 'react'; + +export type UseRedirectionConfig = { + /** + * Should the url be replaced in the history? + * + * @default false + */ + isReplacing?: boolean; + /** + * The destination. + */ + to: string; + /** + * Redirect only when the current path matches the condition. + * + * @param {string} path - The current slug. + * @returns {boolean} True if the path matches. + */ + whenPathMatches?: (path: string) => boolean; +}; + +export const useRedirection = ({ + isReplacing = false, + to, + whenPathMatches, +}: UseRedirectionConfig) => { + const router = useRouter(); + + useEffect(() => { + const shouldRedirect = whenPathMatches + ? whenPathMatches(router.asPath) + : true; + + if (shouldRedirect) { + if (isReplacing) router.replace(to, undefined, { shallow: true }); + else router.push(to); + } + }, [isReplacing, router, to, whenPathMatches]); +}; |
