Created
January 16, 2021 18:58
-
-
Save adamduncan/2e5b9c2eafe74fd9fda902a6ea213ba3 to your computer and use it in GitHub Desktop.
Next.js Router status hook
This file contains hidden or 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
import { useState, useEffect } from 'react'; | |
import Router from 'next/router'; | |
export default function useRouterStatus() { | |
const [isLoading, setIsLoading] = useState(false); | |
const [isError, setIsError] = useState(false); | |
const [error, setError] = useState(); | |
useEffect(() => { | |
const start = () => { | |
setIsLoading(true); | |
}; | |
const complete = () => { | |
setIsLoading(false); | |
setIsError(false); | |
setError(); | |
}; | |
const error = error => { | |
setIsLoading(false); | |
setIsError(true); | |
setError(error); | |
}; | |
Router.events.on('routeChangeStart', start); | |
Router.events.on('routeChangeComplete', complete); | |
Router.events.on('routeChangeError', error); | |
return () => { | |
Router.events.off('routeChangeStart', start); | |
Router.events.off('routeChangeComplete', complete); | |
Router.events.off('routeChangeError', error); | |
}; | |
}, []); | |
return { isLoading, isError, error }; | |
} |
Can be used at the page or component level, to access status of Next's router
. For example:
function SomePage() {
const { isLoading, isError, error } = useRouterStatus();
if (isError) {
return <p>{error}</p>;
}
if (isLoading) {
return <p>Loading...</p>;
}
return (
<>
<h1>Page content</h1>
<p>All good</p>
</>
);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use this hook?