1.0.1 • Published 3 years ago

react-loading-management v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

React-Loading-Management

CodeQL Publish Package to npmjs

React-loading-management was initially developed to use in SatViewer project. But was brought as a standalone package to npm. The package purpose is to make managing loading state for async api requests a breeze.

  • Full Typescript support out of the box
  • Very small dependency
  • No intention to reinvent the wheel
    • React hooks
    • React Context API

Installation

You can install this package from the npm repository by using one of the following commands:

# npm
npm install react-loading-management

# yarn
yarn add react-loading-management

How to use

As this package is using the react context api, we need to wrap our application in a provider to use the loading context.

React

// app.tsx / app.js

function App() {
  return (
    <LoadingProvider>
        <div className="App">
        ...
        </div>
    <LoadingProvider>
  );
}

NextJS

// _app.tsx / _app.js

function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
    return (
        <LoadingProvider>
            <Component {...pageProps} />
        </LoadingProvider>
    );
}

After that we can indicate we are loading at the moment by deconstruct the necessary functions out of our context.

// some react component where we want to display we are loading something. Here a Next.js page is used, but could be an arbitrary component.

const Home: NextPage = () => {
    const { setLoading, stopLoading, isLoading } = useLoadingContext();

    const reject = (ms: number) => new Promise((_resolve, reject) => setTimeout(reject, ms));

    const handleClickWithReject = async () => {
        try {
            setLoading();
            console.log('start');
            await reject(5000);
        } catch {
            console.log('rejected');
        } finally {
            stopLoading();
        }
    };

    return (
        <div>
            {isLoading && <DefaultSpinner />}
            <button onClick={handleClick}>Load async</button>
        </div>
    );
};

TODO

  • Test code against bugs.
  • Finish documentation.
  • Method for encapsulating Promises while loading, so that no manual stop of loading is necessary.

Credits

The default loading indicator was taken from: http://samherbert.net/svg-loaders/