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(core): Allow retries for errored async reads #705

Merged
merged 3 commits into from
Sep 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions src/core/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export const createStore = (
return
}
atomState.c?.() // cancel read promise
delete atomState.e // read error
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was being done when writing to a sync atom, but not an async atom.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow! Nice catch!
Feels like you have fairly deeper understanding of core.

if (isInterruptablePromise(promise)) {
atomState.p = promise // read promise
delete atomState.c // this promise is from another atom state, shouldn't be canceled here
Expand Down
83 changes: 82 additions & 1 deletion tests/error.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ class ErrorBoundary extends Component<
}
render() {
return this.state.hasError ? (
<div>{this.props.message || 'errored'}</div>
<div>
{this.props.message || 'errored'}
<button onClick={() => this.setState({ hasError: false })}>
retry
</button>
</div>
) : (
this.props.children
)
Expand Down Expand Up @@ -447,3 +452,79 @@ describe('throws an error while updating in effect cleanup', () => {
expect(console.error).toHaveBeenCalledTimes(1)
})
})

describe('error recovery', () => {
const counter = atom(0)

const Counter = () => {
const [count, setCount] = useAtom(counter)
return <button onClick={() => setCount(count + 1)}>increment</button>
}

it('recovers from sync errors', async () => {
const syncAtom = atom((get) => {
const value = get(counter)

if (value === 0) {
throw new Error('An error occurred')
}

return value
})

const Display = () => {
return <div>Value: {useAtom(syncAtom)[0]}</div>
}

const { getByText, findByText } = render(
<Provider>
<Counter />
<ErrorBoundary>
<Display />
</ErrorBoundary>
</Provider>
)

await findByText('errored')

fireEvent.click(getByText('increment'))
fireEvent.click(getByText('retry'))
await findByText('Value: 1')
})

it.only('recovers from async errors', async () => {
dai-shi marked this conversation as resolved.
Show resolved Hide resolved
const asyncAtom = atom(async (get) => {
const value = get(counter)
await new Promise((resolve) => {
setTimeout(resolve, 50)
})

if (value === 0) {
throw new Error('An error occurred')
}

return value
})

const Display = () => {
return <div>Value: {useAtom(asyncAtom)[0]}</div>
}

const { getByText, findByText } = render(
<Provider>
<Counter />
<ErrorBoundary>
<Suspense fallback={null}>
<Display />
</Suspense>
</ErrorBoundary>
</Provider>
)

await findByText('errored')

fireEvent.click(getByText('increment'))
fireEvent.click(getByText('retry'))
await findByText('Value: 1')
})
})
56 changes: 1 addition & 55 deletions tests/utils/atomWithObservable.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, Suspense } from 'react'
import { Suspense } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { Observable, Subject } from 'rxjs'
import { useAtom } from '../../src/index'
Expand All @@ -7,31 +7,6 @@ import { getTestProvider } from '../testUtils'

const Provider = getTestProvider()

class ErrorBoundary extends Component<
{ message?: string },
{ hasError: boolean }
> {
constructor(props: { message?: string }) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError() {
return { hasError: true }
}
render() {
return this.state.hasError ? (
<div>
<div>{this.props.message || 'errored'}</div>
<button onClick={() => this.setState({ hasError: false })}>
retry
</button>
</div>
) : (
this.props.children
)
}
}

it('count state', async () => {
const observableAtom = atomWithObservable(
() =>
Expand Down Expand Up @@ -95,32 +70,3 @@ it('writable count state', async () => {
fireEvent.click(getByText('button'))
await findByText('count: 9')
})

// FIXME we would like to support retry
it.skip('count state with error', async () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test wasn't valid - an observable can't recover from an error state. For the notion of "retrying" observables to work, the error would never reach atomWithObservable, so the retrying logic is out of scope for jotai.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, I didn't know about the observable error behavior, and created this test. But, it's an expected behavior.
Now, you find the actual issue of error async reads, and fix it. Very very nice.

const myObservable = new Observable<number>((subscriber) => {
subscriber.error('err1')
subscriber.next(1)
})
const observableAtom = atomWithObservable(() => myObservable)

const Counter = () => {
const [state] = useAtom(observableAtom)

return <div>count: {state}</div>
}

const { findByText, getByText } = render(
<Provider>
<ErrorBoundary>
<Suspense fallback="loading">
<Counter />
</Suspense>
</ErrorBoundary>
</Provider>
)

await findByText('errored')
fireEvent.click(getByText('retry'))
await findByText('count: 1')
})