top-progress-bar.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import Router from 'next/router';
  2. import NProgress from 'nprogress';
  3. let timer: any;
  4. let state: any;
  5. let activeRequests = 0;
  6. const delay = 250;
  7. function load() {
  8. if (state === 'loading') {
  9. return;
  10. }
  11. state = 'loading';
  12. timer = setTimeout(function () {
  13. NProgress.start();
  14. }, delay); // only show progress bar if it takes longer than the delay
  15. }
  16. function stop() {
  17. if (activeRequests > 0) {
  18. return;
  19. }
  20. state = 'stop';
  21. clearTimeout(timer);
  22. NProgress.done();
  23. }
  24. Router.events.on('routeChangeStart', load);
  25. Router.events.on('routeChangeComplete', stop);
  26. Router.events.on('routeChangeError', stop);
  27. if (typeof window !== 'undefined' && typeof window?.fetch === 'function') {
  28. const originalFetch = window.fetch;
  29. window.fetch = async function (...args) {
  30. if (activeRequests === 0) {
  31. load();
  32. }
  33. activeRequests++;
  34. try {
  35. const response = await originalFetch(...args);
  36. return response;
  37. } catch (error) {
  38. return Promise.reject(error);
  39. } finally {
  40. activeRequests -= 1;
  41. if (activeRequests === 0) {
  42. stop();
  43. }
  44. }
  45. };
  46. }
  47. export default function TopProgressBar() {
  48. return null;
  49. }