npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-service

v2.0.0

Published

`useService` react hook. Share a state and an API with multiple components

Downloads

93

Readme

useService react hook

React hook to handle a shared service accross multiple components.

By service we point an instance of a user-defined object using the new operator.

A service may hold a state. That state will be shared to your components. That means your components will be udpated if the service notify it has been updated.

Getting started

just add use-service addon to your project:

npm i use-service

Then you can follow the example at https://github.com/toutpt/use-service/tree/master/src/App.js

example

API

registerService(idOrFunction, func) -> undefined

you have two options:

// foo.js
function $foo() {}

// app.js
registerService('$foo', $foo)

or

// foo.js
function $foo() {}
$foo.id = '$foo'

// app.js
registerService($foo)

useService(id, options) -> service instance

options.subscribe is set by default to true. In case performance are important you can set it to false if you know your component do not display the data of this service.

How to use with typescript

In the following example we build a service able to fetch with abort API. The state management is done by hand to show a real world example.

export class $bar {
	public static $id = '$bar'
	public isLoading: boolean = true
	public error: Error | null = null
	private controller: AbortController | null = null
	public data: any // up to you

	constructor(private $apply: any) {}

	private reset() {
		this.isLoading = true
		this.error = null
		this.$apply()
	}

	abort() {
		if (this.controller) {
			this.controller.abort()
		}
	}

	fetchMe() {
		this.reset()
		this.controller = new AbortController()
		return fetch('/api/bar', { signal: this.controller.signal })
			.then((data) => {
				this.data = data
			})
			.catch((e) => {
				if (e.name !== 'AbortError') {
					this.error = e
				}
			})
			.finally(() => {
				this.isLoading = false
				this.$apply()
			})
	}
}

then, you can register and use it in your component

import React, {useEffect} from 'react';
import { useService } from 'use-service';
// this is one of the main difference
import { $foo as FooService } from './foo.service.ts';

export function MyBar() {
    const $foo : FooService = useService('$foo');
    useEffect(() => {
        $foo.fetchMe();
        return () => $foo.abort();
    }, []);

    if ($foo.error) {
        return (
            <div className="alert alert-danger">
                <p>Could not load: {$foo.error.message}</p>
                <button className="btn btn-default" onClick={() => $foo.fetchMe()}>re try<button>
            </div>
        );
    }

    if ($foo.isLoading) {
        return "loading ... " // use your loading feedback component
    }

    return (
        <div className="foo">
            // display your $foo.data
        </div>
    );
}