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

jotai-async

v0.4.1

Published

Async side effects for jotai

Downloads

40

Readme

jotai-async

image

An extension for Jotai that simplifies asynchronous state management in React applications.

Features

  • Simplifies handling of asynchronous data fetching and mutations.
  • Provides queryAtom and mutationAtom for managing async operations.
  • Includes a useQueryAtom hook for seamless integration with React components.

Installation

npm install jotai-async

or

yarn add jotai-async

or

pnpm install jotai-async

Usage

Importing

import { queryAtom, mutationAtom } from 'jotai-async';
import { useQueryAtom } from 'jotai-async/react';

Creating a Query Atom

const userQueryEffect = queryAtom(async ({ get, set, signal }) => {
  const response = await fetch('/api/user', { signal });
  if (!response.ok) throw new Error('Failed to fetch user data');
  const data = await response.json();
  return data;
});

Using userQueryEffect in a Component

import React, { Suspense } from "react";
import { useQueryAtom } from 'jotai-async/react';

const UserProfile = () => {
  const { data, isLoading, error } = useQueryAtom(userQueryEffect);

  if (error) return <div>Error loading user data: {error.message}</div>;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
}

const App = () => {
  return <Suspense fallback={"Loading"}>
    <UserProfile/>
  </Suspense>
}

Creating a Mutation Atom

const updateUserMutation = mutationAtom(async ({ get, set, signal }, userData) => {
  const response = await fetch('/api/user', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData),
    signal,
  });
  if (!response.ok) throw new Error('Failed to update user data');
  const data = await response.json();
  return data;
});

Using the Mutation Atom

import React from 'react';
import { useAtom } from 'jotai';
import { updateUserMutation } from './atoms';

function UpdateUserForm() {
  const updateUser = useAtomSet(updateUserMutation);
  const [formState, setFormState] = useState({ name: '', email: '' });

  const handleSubmit = async (event) => {
    event.preventDefault();

    updateUser(formState).catch(error => {
      console.error(error);
    })
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields for name and email */}
      <button type="submit">Update User</button>
    </form>
  );
}

API Reference

queryAtom(callback, options)

Creates an atom for managing asynchronous data fetching.

  • Parameters:
    • callback: An asynchronous function that fetches data.
    • options (optional): An object with the following properties:
      • cacheKey: A CacheKeyAtom used for caching purposes.
      • debugLabel: A string label for debugging.

Returns: A QueryAtom with additional properties and methods.

Properties of QueryAtom

  • mutation: A writable atom for manually triggering the query.
  • $isFetching: An atom representing the fetching state (boolean).
  • $data: An atom holding the fetched data (Result | null).
  • abort: A writable atom to abort the ongoing fetch.
  • $error: An atom holding any errors encountered (Error | null).
  • $status: An atom representing the status ('init' | 'loading' | 'fetching' | 'success' | 'error').
  • $isLoading: An atom indicating if loading is in progress (boolean).
  • $promise: An atom holding the promise of the fetch operation (Promise<Result> | null).

mutationAtom(callback)

Creates an atom for managing asynchronous mutations.

  • Parameters:
    • callback: An asynchronous function that performs the mutation.

Returns: A writable atom with additional properties and methods.

Properties of mutationAtom

  • $data: An atom holding the result of the mutation (Result | null).
  • $error: An atom holding any errors encountered (Error | null).
  • $status: An atom representing the status ('init' | 'loading' | 'fetching' | 'success' | 'error').
  • $isLoading: An atom indicating if the mutation is in progress (boolean).
  • $isFetching: An atom indicating if fetching is in progress (boolean).
  • $promise: An atom holding the promise of the mutation (Promise<Result> | null).
  • abort: A writable atom to abort the ongoing mutation.

useQueryAtom(queryAtom)

A React hook for using a QueryAtom in a component.

  • Parameters:
    • queryAtom: The QueryAtom to be used.

Returns: An object containing:

  • data: The fetched data or null.
  • isLoading: true if loading is in progress.
  • isFetching: true if fetching is in progress.
  • status: The status of the query ('init' | 'loading' | 'fetching' | 'success' | 'error').
  • error: Any error encountered during fetching.

Types

AsyncCallback<Result, Payload>

An asynchronous function that performs an operation and returns a Promise<Result>.

type AsyncCallback<Result, Payload> = (
  options: AsyncCallbackOptions,
  payload: Payload
) => Promise<Result>;

AsyncCallbackOptions

Options provided to the AsyncCallback function.

  • get: Jotai's Getter.
  • set: Jotai's Setter.
  • signal: An AbortSignal to handle cancellation.

CacheKey

An array of strings or numbers used for caching.

type CacheKey = Array<string | number>;

CacheKeyAtom

An atom or promise that resolves to a CacheKey.

type CacheKeyAtom = Atom<CacheKey | Promise<CacheKey>>;

Contributing

Contributions are welcome! Please feel free to open issues or submit pull requests.

License

MIT