This code allow for smarter handling of nprogress using event observers that check progress of all observing events. This also adds ability to support error conditions when observeable callbacks fail.
Install nprogress:
yarn add nprogress
Copy the nprogress.js
file into lib/nprogress.js
.
To add default route event observers for NextJS, add into _app.js
(preferred):
import React from 'react';
// Loads nprogress & modifications and adds NextJS route observers
import 'lib/nprogress';
const MyApp = ({ Component, pageProps }) => {
return <Component {...pageProps} />
};
export default MyApp;
You can wrap callback functions with nprogress.observe()
to have start, stop, and error progress bars displayed while performing actions, such as fetching data from an API or uploading an image.
import nprogress from 'lib/nprogress';
export async function fetchFromApi() {
return nprogress.observe(async () => {
const data = await axios.get('https://gleu.ch');
return data.body;
});
});
Observable events are handled with Promise.all
. Therefore you can await multiple events with nprogress.observe()
, e.g. nprogress.observe(fn1, fn2, ...)
.
import nprogress from 'lib/nprogress';
export async function fetchDataPoints() {
const [dogs, cats, fish] = nprogress.observe(
() => axios.get('http://data.tld/results/dogs.json'),
() => axios.get('http://data.tld/results/cats.json'),
() => axios.get('http://data.tld/results/fish.json'),
);
return { dogs, cats, fish };
};
A simplified version of the nprogress stylesheet can be used to set CSS vars for changing the color on regular and error events. This CSS does not support optional loading spinner.
If you wish to use the full Nprogress CSS, you will need to make sure to add a case for when error
className is added to the #nprogress
element.