From 40ef9bec4f1d03c657a85724449aacd7f345c173 Mon Sep 17 00:00:00 2001 From: Iwo Plaza Date: Mon, 8 Jul 2024 23:45:18 +0200 Subject: [PATCH] v0.1.0 --- README.md | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++- package.json | 2 +- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ede12b4..57dc5c0 100644 --- a/README.md +++ b/README.md @@ -50,4 +50,70 @@ immediately. Building data graphs with these dual-natured (sometimes async, sometimes sync) atoms as a base can lead to unnecessary rerenders, stale values and micro-suspensions (in case of React) if not handled with care. `jotai-derive` provides a primitive for building asynchronous data graphs -that act on values as soon as they are available (either awaiting for them, or acting on them synchronously). \ No newline at end of file +that act on values as soon as they are available (either awaiting for them, or acting on them synchronously). + +## Recipes + +### Single async dependency + +```ts +import { derive } from 'jotai-derive'; + +// Atom> +const uppercaseNameAtom = derive( + [userAtom], // will be awaited only when necessary + (user) => user.name.toUppercase(), +); +``` + +### Multiple async dependencies + +```ts +import { derive } from 'jotai-derive'; + +// Atom> +const welcomeMessageAtom = derive( + [userAtom, serverNameAtom], + (user, serverName) => `Welcome ${user.name} to ${serverName}!`, +); +``` + +### Conditional dependency + +```ts +// pipes allow for cleaner code when using `soon` directly. +import { pipe } from 'remeda'; +import { soon } from 'jotai-derive'; + +const queryAtom: Atom> = ...; + +const isAdminAtom: Atom> = ...; + +const restrictedItemAtom = atom((get) => + pipe( + get(isAdminAtom), + soon((isAdmin) => (isAdmin ? get(queryAtom) : null)) + ) +); +``` + +### Conditional dependency (multiple conditions) + +```ts +// pipes allow for cleaner code when using `soon` directly. +import { pipe } from 'remeda'; +import { soon, soonALl } from 'jotai-derive'; + +const queryAtom: Atom> = ...; + +const isAdminAtom: Atom> = ...; +const enabledAtom: Atom> = ...; + +const restrictedItemAtom = atom((get) => + pipe( + soonAll(get(isAdminAtom), get(enabledAtom)), + soon(([isAdmin, enabled]) => (isAdmin && enabled ? get(queryAtom) : null)) + ) +); + +``` diff --git a/package.json b/package.json index 30c9135..7e0d3e3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "jotai-derive", - "version": "0.0.0", + "version": "0.1.0", "type": "module", "description": "Jōtai utilities that help with asynchronous atoms", "packageManager": "pnpm@8.15.0",