Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(utils): Unwrap loadable/selectAtom promise types #844

Merged
merged 2 commits into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/utils/loadable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import { atom } from 'jotai'
import type { Atom } from 'jotai'
import { createMemoizeAtom } from './weakCache'

type ResolveType<T> = T extends Promise<infer V> ? V : T

const memoizeAtom = createMemoizeAtom()

type Loadable<Value> =
| { state: 'loading' }
| { state: 'hasError'; error: unknown }
| { state: 'hasData'; data: Value }
| { state: 'hasData'; data: ResolveType<Value> }

export function loadable<Value>(anAtom: Atom<Value>): Atom<Loadable<Value>> {
return memoizeAtom(() => {
Expand All @@ -18,7 +20,7 @@ export function loadable<Value>(anAtom: Atom<Value>): Atom<Loadable<Value>> {
const ref = get(refAtom)
let curr = ref.prev
try {
const value = get(anAtom)
const value = get(anAtom) as ResolveType<Value>
if (curr?.state !== 'hasData' || !Object.is(curr.data, value)) {
curr = { state: 'hasData', data: value }
}
Expand Down
6 changes: 4 additions & 2 deletions src/utils/selectAtom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@ import { atom } from 'jotai'
import type { Atom } from 'jotai'
import { createMemoizeAtom } from './weakCache'

type ResolveType<T> = T extends Promise<infer V> ? V : T

const memoizeAtom = createMemoizeAtom()

export function selectAtom<Value, Slice>(
anAtom: Atom<Value>,
selector: (v: Value) => Slice,
selector: (v: ResolveType<Value>) => Slice,
equalityFn: (a: Slice, b: Slice) => boolean = Object.is
): Atom<Slice> {
return memoizeAtom(() => {
// TODO we should revisit this for a better solution than refAtom
const refAtom = atom(() => ({} as { prev?: Slice }))
const derivedAtom = atom((get) => {
const slice = selector(get(anAtom))
const slice = selector(get(anAtom) as ResolveType<Value>)
const ref = get(refAtom)
if ('prev' in ref && equalityFn(ref.prev as Slice, slice)) {
return ref.prev as Slice
Expand Down
5 changes: 4 additions & 1 deletion tests/utils/loadable.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,8 @@ const LoadableComponent = ({ asyncAtom }: LoadableComponentProps) => {
return <>{String(value.error)}</>
}

return <>Data: {value.data}</>
// this is to ensure correct typing
const data: number | string = value.data

return <>Data: {data}</>
}
49 changes: 48 additions & 1 deletion tests/utils/selectAtom.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef } from 'react'
import { Suspense, useEffect, useRef } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { atom } from 'jotai'
import { selectAtom, useAtomValue, useUpdateAtom } from 'jotai/utils'
Expand Down Expand Up @@ -58,6 +58,53 @@ it('selectAtom works as expected', async () => {
await findByText('a: 3')
})

it('selectAtom works with async atom', async () => {
const bigAtom = atom({ a: 0, b: 'othervalue' })
const bigAtomAsync = atom((get) => Promise.resolve(get(bigAtom)))
const littleAtom = selectAtom(bigAtomAsync, (v) => v.a)

const Parent = () => {
const setValue = useUpdateAtom(bigAtom)
return (
<>
<button
onClick={() =>
setValue((oldValue) => ({ ...oldValue, a: oldValue.a + 1 }))
}>
increment
</button>
</>
)
}

const Selector = () => {
const a = useAtomValue(littleAtom)
return (
<>
<div>a: {a}</div>
</>
)
}

const { findByText, getByText } = render(
<Provider>
<Suspense fallback={null}>
<Parent />
<Selector />
</Suspense>
</Provider>
)

await findByText('a: 0')

fireEvent.click(getByText('increment'))
await findByText('a: 1')
fireEvent.click(getByText('increment'))
await findByText('a: 2')
fireEvent.click(getByText('increment'))
await findByText('a: 3')
})

it('do not update unless equality function says value has changed', async () => {
const bigAtom = atom({ a: 0 })
const littleAtom = selectAtom(
Expand Down