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
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();
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 ❤️
pinussilvestrus / use-spinner
Add a simple loading spinner to your async JS calls - built for the browser.
use-spinner
Add a simple loading spinner to your async JS calls - built for the browser.
Installation
$ npm install --save use-spinner
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();
Options
The API accepts a second argument configuring the wrapped function. This defaults to:
{
container: 'body'
}
- container: a selector or a DOM element that appends the loading spinner.
License
MIT
Top comments (3)
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 toggleshow
class?Not everything needs to be a hook, this is one example of this.
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.