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

zustand-async-slice

v1.0.5

Published

Zustand Utility For Creating Async Slice easily

Downloads

25

Readme

Zustand Async Slice

🦄 Zustand Utility For Creating Async Slice easily in TypeScript!

codecov

Introduce

The asyncSlice function automatically creates and manages various states inside the Zustand Store by simply passing the slice name to name and the asynchronous function to asyncFn.

It even provides full support for TypeScript. 🔥

It minimizes the hassle for developers to manually write types, ensuring a smooth developer experience

If we pass hello, it generates like that.

Install

yarn add zustand-async-slice

Usage

Auto Generated States in Store ♥️

name: hello

  • isHelloFetching: boolean
  • isHelloError: boolean
  • helloData: Data | undefined
    • type parameter Data is inferred return type of asyncFn
  • runHello: (params: Params, callbacks?: Callbacks) => void
  • runHello: (callbacks?: Callbacks) => void
    • type parameter Params should be passed second argument of asyncSlice
    • is there no params? then no arg function will be generated ‼
    • callbacks are onRun, onSettled, onSuccess, onError. You can pass callbacks from the caller at the runtime or definition of the async slice.
  • runHelloAsync: (params: Params) => Promise<Data>
  • runHelloAsync: () => Promise<Data>
    • returnning Promise<Data> function is available too

Step 1. Create Async Slice with asyncSlice

Let's create a async slice named Hello by passing Hello string to name parameter.

No Parameter Version

const helloSlice = asyncSlice<MyStoreState>()({
  name: 'hello',
  asyncFn: async ({ get, set }) => {
    await new Promise((r) => setTimeout(r, 3000)); // wait 3 seconds
    return 1;
  },
  // on asyncFn has been called
  onRun: ({ get, set }) => {},
  // on asyncFn has been completed as success or failure
  onSettled: ({ get, set, data, error, isError, isSuccess }) => {},
  // on asyncFn has been completed as success
  onSuccess: ({ get, set, data }) => {},
  // on asyncFn has been completed as error
  onError: ({ get, set, error }) => {},
});

[!NOTE] Yes, get and set are those in Zustand store API. The type of get and set are inferred from first type parameter of asyncSlice(MyStoreState).

With Parameter Version

const helloSlice = asyncSlice<MyStoreState, { arg1: number; arg2: string }>()({
  name: 'Hello',
  asyncFn: async ({ arg1, arg2 }, { get, set }) => {
    await new Promise((r) => setTimeout(r, 3000)); // wait 3 seconds
    return 1;
  },
  onRun: ({ params, get, set }) => {},
  onSettled: ({ params, get, set, data, error, isError, isSuccess }) => {},
  onSuccess: ({ params, get, set, data }) => {},
  onError: ({ params, get, set, error }) => {},
});

Check that the parameter type of the async function is defined as the second argument of asyncSlice and that params are added to each callback function.

[!TIP] Why currying? ()(...) > Read on Zustand TS docs

Step 2. Inject slice into original store create process.

import type { WithAsyncState } from 'zustand-async-slice';

export type MyStoreState = { age: number };

export const useMyStore = create<WithAsyncState<typeof helloSlice>>()((set, get, store) => ({
  age: 0,
  ...helloSlice(set, get, store), // Inject
}));

Thanks to WrapAsyncState, we can simply pass the slice's type to it, and without needing to redefine the existing Store's type using &, we can just pass it as a type argument to create.

Step 3. Use the store in the way you enjoy.

Full Example

import { asyncSlice, WithAsyncState } from 'zustand-async-slice';

type MyState = { age: number; };

const helloSlice = asyncSlice<MyState>()({
  name: 'hello',
  asyncFn: async ({ set }) => { // can be async or not
    set({ age: 1 });
    return 1;
  },
});

const useMyStore = create<WithAsyncState<typeof helloSlice>>((...s) => ({
  age: 0,
  ...helloSlice(...s),
}));