From 92bac938dd83edd9ff17ad77d7699c87cfa7a1a8 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 24 Jun 2021 20:16:54 +0200 Subject: [PATCH] fix with-loading example for next 11 (#26569) ## Documentation / Examples - [X] Make sure the linting passes This PR updates the with-loading example to follow the documentation of router events for next 11 --- examples/with-loading/pages/_app.js | 32 +++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/examples/with-loading/pages/_app.js b/examples/with-loading/pages/_app.js index edb59d1190492..f61239140652b 100644 --- a/examples/with-loading/pages/_app.js +++ b/examples/with-loading/pages/_app.js @@ -1,16 +1,32 @@ -import Router from 'next/router' +import { useEffect } from 'react' import Link from 'next/link' import Head from 'next/head' +import { useRouter } from 'next/router' import NProgress from 'nprogress' -Router.events.on('routeChangeStart', (url) => { - console.log(`Loading: ${url}`) - NProgress.start() -}) -Router.events.on('routeChangeComplete', () => NProgress.done()) -Router.events.on('routeChangeError', () => NProgress.done()) - export default function App({ Component, pageProps }) { + const router = useRouter() + + useEffect(() => { + const handleStart = (url) => { + console.log(`Loading: ${url}`) + NProgress.start() + } + const handleStop = () => { + NProgress.done() + } + + router.events.on('routeChangeStart', handleStart) + router.events.on('routeChangeComplete', handleStop) + router.events.on('routeChangeError', handleStop) + + return () => { + router.events.off('routeChangeStart', handleStart) + router.events.off('routeChangeComplete', handleStop) + router.events.off('routeChangeError', handleStop) + } + }, [router]) + return ( <>