Skip to content

Commit

Permalink
docs(advanced-recipes): atomWithRefresh: derived atom with refresh (p…
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-smart authored Jan 26, 2022
1 parent 6ddbc69 commit 6239409
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions docs/advanced-recipes/atom-creators.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,62 @@ const StylePreview = () => {
)
}
```

## atomWithRefresh

> `atomWithRefresh` creates a derived atom that can be force-refreshed, by using
> the update function.
This is helpful when you need to refresh asynchronous data after performing a
side effect.

It can also be used to implement "pull to refresh" functionality.

```ts
import { atom, Getter } from 'jotai'

export function atomWithRefresh<T>(fn: (get: Getter) => T) {
const refreshCounter = atom(0)

return atom(
(get) => {
get(refreshCounter)
return fn(get)
},
(_, set) => set(refreshCounter, (i) => i + 1)
)
}
```

Here's how you'd use it to implement an refreshable source of data:

```ts
import { atomWithRefresh } from 'XXX'

const postsAtom = atomWithRefresh((get) =>
fetch('https://jsonplaceholder.typicode.com/posts').then((r) => r.json())
)
```

In a component:

```ts
const PostsList = () => {
const [posts, refreshPosts] = useAtom(postsAtom)

return (
<div>
<ul>
{posts.map((post: any) => (
<li key={post.id}>{post.title}</li>
))}
</ul>

{/* Clicking this button will re-fetch the posts */}
<button type="button" onClick={refreshPosts}>
Refresh posts
</button>
</div>
)
}
```

0 comments on commit 6239409

Please sign in to comment.