DEV Community

Niklas Kiefer
Niklas Kiefer

Posted on

use-spinner - Show loading spinners for your asynchronous calls

Hello community 👋

Sometimes calls can take longer, so showing a loading spinner becomes an option to fill the gap. I was tired of configuring such spinners times and times again.

Yesterday I built a tiny Javascript library called use-spinner that simply wraps asynchronous calls into a new function adding a loading spinner to the DOM.

Simply install the module

$ npm install --save use-spinner
Enter fullscreen mode Exit fullscreen mode

and embed it in your Node.js styled application.

import useSpinner from 'use-spinner';

import 'use-spinner/assets/use-spinner.css';

const mySlowCall = async () => {
  return await fetch(/*...*/);
}

const spinned = useSpinner(mySlowCall);

await spinned();
Enter fullscreen mode Exit fullscreen mode

Alt Text

Of course, it is rather rudimentary right now and the spinner itself is hardly customizable. However, I like the easiness of integration to existing functions without much configuration.

Enjoy ❤️

GitHub logo pinussilvestrus / use-spinner

Add a simple loading spinner to your async JS calls - built for the browser.

use-spinner

CI npm bundle size

Add a simple loading spinner to your async JS calls - built for the browser.

Installation

$ npm install --save use-spinner
Enter fullscreen mode Exit fullscreen mode

Usage

import useSpinner from 'use-spinner';

import 'use-spinner/assets/use-spinner.css';

const fn = async () => {
  await new Promise(resolve => setTimeout(() => {
    console.log('done.');
    resolve();
  }, 2000));
};

// wrap your asynchronous function
const spinnedFn = useSpinner(fn, {
  container: 'body'
});

// execute with a loading spinner
await spinnedFn();
Enter fullscreen mode Exit fullscreen mode

Screencast

License

MIT

Discussion (3)

Collapse
devtalhaakbar profile image
Muhammad Talha Akbar

Nice. However, my other concerns aside, you are using appending the spinner on every useSpinner call. You might need to send multiple requests at the same time which will append multiple spinners. Perhaps, you append the spinner at the creation already and then just toggle show class?

Collapse
ivanjeremic profile image
Ivan Jeremic

Not everything needs to be a hook, this is one example of this.

Collapse
pinussilvestrus profile image
Niklas Kiefer Author

Interesting you call it a hook although the term was nowhere mentioned. 🙂

That's the way of API design: make it familiar to what people are used about. I agree not everything has to be a hook. But make it easy to consume.