Skip to content

Commit

Permalink
v0.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
iwoplaza committed Jul 8, 2024
1 parent 5f515b7 commit 40ef9be
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
68 changes: 67 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
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<string | Promise<string>>
const uppercaseNameAtom = derive(
[userAtom], // will be awaited only when necessary
(user) => user.name.toUppercase(),
);
```

### Multiple async dependencies

```ts
import { derive } from 'jotai-derive';

// Atom<string | Promise<string>>
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<RestrictedItem | Promise<RestrictedItem>> = ...;

const isAdminAtom: Atom<boolean | Promise<boolean>> = ...;

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<RestrictedItem | Promise<RestrictedItem>> = ...;

const isAdminAtom: Atom<boolean | Promise<boolean>> = ...;
const enabledAtom: Atom<boolean | Promise<boolean>> = ...;

const restrictedItemAtom = atom((get) =>
pipe(
soonAll(get(isAdminAtom), get(enabledAtom)),
soon(([isAdmin, enabled]) => (isAdmin && enabled ? get(queryAtom) : null))
)
);

```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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": "[email protected]",
Expand Down

0 comments on commit 40ef9be

Please sign in to comment.