Reputation: 613
I am trying to add a loading screen whenever a URL change detect, So I am trying to put this code inside my _app.js file.
import Router from "next/router";
export default function App({ Component, pageProps }) {
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
const start = () => {
console.log("start");
setLoading(true);
};
const end = () => {
console.log("findished");
setLoading(false);
};
Router.events.on("routeChangeStart", start);
Router.events.on("routeChangeComplete", end);
Router.events.on("routeChangeError", end);
return () => {
Router.events.off("routeChangeStart", start);
Router.events.off("routeChangeComplete", end);
Router.events.off("routeChangeError", end);
};
}, []);
return (
<>
{loading ? (
<h1>Loading...</h1>
) : (
<Component {...pageProps} />
)}
</>
);
}
But the issue is I am not able to attact redux.
My current code with Redux is this :
import React, { useEffect } from "react"
import { wrapper } from "../redux/store"
import Layout from '../components/Layout';
import '../styles/globals.css'
import '../styles/media.css'
const MyApp = ({ Component, pageProps }) =>(
<Layout>
<Component {...pageProps} />
</Layout>
);
export default wrapper.withRedux(MyApp);
Can someone help me?
Upvotes: 0
Views: 627
Reputation: 1315
//Loading Component
const Loading = ()=>{
return (
<div> Loading gif here </div>
)
}
const App = ()=>{
const [currentPathname, setCurrentPathname] = useState<string>('');
const router = useRouter();
const [loading, setLoading] = useState<boolean>(false);
useEffect(() => {
if (router.isReady) {
if (router.pathname !== currentPathname) {
setLoading(true);
setCurrentPathname(router.pathname);
setTimeout(() => {
setLoading(false);
}, 3000);
}
}
}, [router, router.pathname]);
return (
<Layout>
{loading && <Loading />}
<Component {...pageProps} />
</Layout>
)
}
I assume that you have the loading component with some sort of loading gif. I just check this solution inside my next app. Inside the useEffect, just check if the current path name is not the same then set the loading state to true to enable the loading component to show. Once it is enabled, set the current path name inside the local state and use a set timeout function to stop the loading after few seconds. In example, you will notice that I'm changing the loading state after 3 seconds
Upvotes: 1