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

restater

v0.0.12

Published

Tiny hook-based state management tool for React

Downloads

9

Readme

Restater · NPM Version Build Status

Tiny hook-based state management tool for React

Table of content

Getting started

Install

With NPM

npm i restater

With yarn

yarn add restater

Usage

Create a store

To create a simple state store, use the createStore function from restater.

It will return a tuple with a Provider and a StoreContext.

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'restater';

// Define the initial state
const initialState = {
  username: 'restater',
  followers: 42,
  isPublic: true,
};

// Create the store
const [Provider, MyStore] = createStore(initialState);

ReactDOM.render(
  // Wrap your component in the Provider
  <Provider>
    <App />
  </Provider>,
  document.getElementById('root'),
);

export { MyStore };

Use the store

In order to use the store, use the useStore hook from restater.

The useStore hook takes a StoreContext and a property-name, and returns a state and a setState tuple, just as useState.

import React from 'react';
import { useStore } from 'restater';
import { MyStore } from '../index';

const App = () => {
  const [username, setUsername] = useStore(MyStore, 'username');

  return <div>My name is: {username}</div>;
};

Updating the username is easy.

setUsername('cool-new-username');

Any component that is using the username from the store will now get updated, but without affecting any components "in between".


Create an Async Store

A store can also hold async values, and for that, we create a separate kind of store using createAsyncStore.
Again, we provide initial values, but the store will treat these values as promises that needs to be resolved before being set.

Creating the store will work the same as before.

import React from 'react';
import ReactDOM from 'react-dom';
import { createAsyncStore } from 'restater';

// Define the initial state
const initialState = {
  username: 'restater',
  followers: 42,
  isPublic: true,
};

// Create an *async* store
const [Provider, MyAsyncStore] = createAsyncStore(initialState);

ReactDOM.render(
  // Wrap your component in the Provider
  <Provider>
    <App />
  </Provider>,
  document.getElementById('root'),
);

export { MyAsyncStore };

Use the async store

When we use an Async Store, the state and setState functions behave a little different.
Instead of username containing the value directly, it will contain an object with three properties: data, state, and error.

  • data contains the value of username.
  • state represents the current state of the promise, and can be either initial, loading, failed or completed.
  • error contains the error that is thrown, if the promise fails.

This enables us to render something conditionally, based on the current state of the store data we want to use.

Note that data will only exist when state is either initial or completed, and error will only exist if state is failed.

import React from 'react';
import { useAsyncStore } from 'restater';
import { MyAsyncStore } from '../index';

const App = () => {
  const [username, setUsername] = useAsyncStore(MyAsyncStore, 'username');

  if (username.state === 'initial') {
    return <div>The initial name is: {username.data}</div>;
  }

  if (username.state === 'completed') {
    return <div>My name is: {username.data}</div>;
  }

  if (username.state === 'loading') {
    return <div>Loading ...</div>;
  }

  if (username.state === 'failed') {
    return <div>Something failed: {username.error.message}</div>;
  }
};

Because the store is async, the setUsername now expects a promise instead of a raw value.

const getUpdatedUsername = async () => {
  const request = await fetch('http://username-api.com');
  const result = await request.json();

  // Result is the new username
  return result;
};

setUsername(getUpdatedUsername());

This will cause the username.state to go into loading in any component that is using the username from the store.

Note that the setUsername itself returns a promise, so we can await it and do something after the username.state has gone into either completed or failed.

await setUsername(getUpdatedUsername());
// Do something after the username has been updated

When using an Async Store, the setUsername function takes an optional options object as the second argument:

setUsername(getUpdatedUsername(), { skipLoading: true });

Setting skipLoading to true will bypass the loading step.
This will make username.state go directly from initial to completed or failed.
If ``username.stateis already incompleted, it will stay there, or go to failed`.

Helper functions

To avoid wrapping too many providers in each other, you can use the helper function combineProviders which will combine a list of providers into one.

import { combineProviders } from 'restater';

const [Provider1, Context1] = createStore({ /* intital state */ });
const [Provider2, Context2] = createAsyncStore({ /* intital state */ });

// Combine the providers
const Provider = combineProviders([Provider1, Provider2]);

ReactDOM.render(
  // Use the reduced provider and provide access to both stores
  <Provider>
    <App />
  </Provider>,
  document.getElementById('root'),
);

License

This project is licensed under the MIT License

Get Help

Contribute

Issues

In the case of a bug report, bugfix or a suggestions, please feel very free to open an issue.

Pull request

Pull requests are always welcome, and I'll do my best to do reviews as fast as I can.