Skip to content

feat: add reset error boundary component #980

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

Merged
merged 1 commit into from
Sep 11, 2020
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
62 changes: 48 additions & 14 deletions docs/src/pages/docs/guides/suspense.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,57 @@ In addition to queries behaving differently in suspense mode, mutations also beh

## Resetting Error Boundaries

Whether you are using **suspense** or **useErrorBoundaries** in your queries, you will need to know how to use the `queryCache.resetErrorBoundaries` function to let queries know that you want them to try again when you render them again.
Whether you are using **suspense** or **useErrorBoundaries** in your queries, you will need a way to let queries know that you want to try again when re-rendering after some error occured.

How you trigger this function is up to you, but the most common use case is to do it in something like `react-error-boundary`'s `onReset` callback:
Query errors can be reset with the `ReactQueryErrorResetBoundary` component or with the `useErrorResetBoundary` hook.

When using the component it will reset any query errors within the boundaries of the component:

```js
import { ReactQueryErrorResetBoundary } from 'react-query'
import { ErrorBoundary } from 'react-error-boundary'

const App: React.FC = () => (
<ReactQueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<Button onClick={() => resetErrorBoundary()}>Try again</Button>
</div>
)}
>
<Page />
</ErrorBoundary>
)}
</ReactQueryErrorResetBoundary>
)
```

When using the hook it will reset any query errors within the closest `ReactQueryErrorResetBoundary`. If there is no boundary defined it will reset them globally:

```js
import { queryCache } from "react-query";
import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary
onReset={() => queryCache.resetErrorBoundaries()}
fallbackRender={({ error, resetErrorBoundary }) => (
<div>
There was an error!
<Button onClick={() => resetErrorBoundary()}>Try again</Button>
</div>
)}
>
import { useErrorResetBoundary } from 'react-query'
import { ErrorBoundary } from 'react-error-boundary'

const App: React.FC = () => {
const { reset } = useErrorResetBoundary()
return (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<Button onClick={() => resetErrorBoundary()}>Try again</Button>
</div>
)}
>
<Page />
</ErrorBoundary>
)
}
```

## Fetch-on-render vs Render-as-you-fetch
Expand Down
51 changes: 51 additions & 0 deletions src/react/ReactQueryErrorResetBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React from 'react'

// CONTEXT

interface ReactQueryErrorResetBoundaryValue {
clearReset: () => void
isReset: () => boolean
reset: () => void
}

function createValue(): ReactQueryErrorResetBoundaryValue {
let isReset = true
return {
clearReset: () => {
isReset = false
},
reset: () => {
isReset = true
},
isReset: () => {
return isReset
},
}
}

const context = React.createContext(createValue())

// HOOK

export const useErrorResetBoundary = () => React.useContext(context)

// COMPONENT

export interface ReactQueryErrorResetBoundaryProps {
children:
| ((value: ReactQueryErrorResetBoundaryValue) => React.ReactNode)
| React.ReactNode
}

export const ReactQueryErrorResetBoundary: React.FC<ReactQueryErrorResetBoundaryProps> = ({
children,
}) => {
const value = React.useMemo(() => createValue(), [])
return (
<context.Provider value={value}>
{typeof children === 'function'
? (children as Function)(value)
: children}
</context.Provider>
)
}
5 changes: 5 additions & 0 deletions src/react/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ export {
useQueryCache,
} from './ReactQueryCacheProvider'
export { ReactQueryConfigProvider } from './ReactQueryConfigProvider'
export {
ReactQueryErrorResetBoundary,
useErrorResetBoundary,
} from './ReactQueryErrorResetBoundary'
export { useIsFetching } from './useIsFetching'
export { useMutation } from './useMutation'
export { useQuery } from './useQuery'
Expand All @@ -15,3 +19,4 @@ export type { UseInfiniteQueryObjectConfig } from './useInfiniteQuery'
export type { UsePaginatedQueryObjectConfig } from './usePaginatedQuery'
export type { ReactQueryCacheProviderProps } from './ReactQueryCacheProvider'
export type { ReactQueryConfigProviderProps } from './ReactQueryConfigProvider'
export type { ReactQueryErrorResetBoundaryProps } from './ReactQueryErrorResetBoundary'
133 changes: 133 additions & 0 deletions src/react/tests/suspense.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import * as React from 'react'
import { sleep, queryKey, mockConsoleError } from './utils'
import { useQuery } from '..'
import { queryCache } from '../../core'
import {
ReactQueryErrorResetBoundary,
useErrorResetBoundary,
} from '../ReactQueryErrorResetBoundary'

describe("useQuery's in Suspense mode", () => {
it('should not call the queryFn twice when used in Suspense mode', async () => {
Expand Down Expand Up @@ -192,6 +196,135 @@ describe("useQuery's in Suspense mode", () => {
consoleMock.mockRestore()
})

it('should retry fetch if the reset error boundary has been reset', async () => {
const key = queryKey()

let succeed = false
const consoleMock = mockConsoleError()

function Page() {
useQuery(
key,
async () => {
await sleep(10)
if (!succeed) {
throw new Error('Suspense Error Bingo')
} else {
return 'data'
}
},
{
retry: false,
suspense: true,
}
)
return <div>rendered</div>
}

const rendered = render(
<ReactQueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
<div>error boundary</div>
<button
onClick={() => {
resetErrorBoundary()
}}
>
retry
</button>
</div>
)}
>
<React.Suspense fallback="Loading...">
<Page />
</React.Suspense>
</ErrorBoundary>
)}
</ReactQueryErrorResetBoundary>
)

await waitFor(() => rendered.getByText('Loading...'))
await waitFor(() => rendered.getByText('error boundary'))
await waitFor(() => rendered.getByText('retry'))
fireEvent.click(rendered.getByText('retry'))
await waitFor(() => rendered.getByText('error boundary'))
await waitFor(() => rendered.getByText('retry'))
succeed = true
fireEvent.click(rendered.getByText('retry'))
await waitFor(() => rendered.getByText('rendered'))

consoleMock.mockRestore()
})

it('should retry fetch if the reset error boundary has been reset with global hook', async () => {
const key = queryKey()

let succeed = false
const consoleMock = mockConsoleError()

function Page() {
useQuery(
key,
async () => {
await sleep(10)
if (!succeed) {
throw new Error('Suspense Error Bingo')
} else {
return 'data'
}
},
{
retry: false,
suspense: true,
}
)
return <div>rendered</div>
}

function App() {
const { reset } = useErrorResetBoundary()
return (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
<div>error boundary</div>
<button
onClick={() => {
resetErrorBoundary()
}}
>
retry
</button>
</div>
)}
>
<React.Suspense fallback="Loading...">
<Page />
</React.Suspense>
</ErrorBoundary>
)
}

const rendered = render(<App />)

await waitFor(() => rendered.getByText('Loading...'))
await waitFor(() => rendered.getByText('error boundary'))
await waitFor(() => rendered.getByText('retry'))
fireEvent.click(rendered.getByText('retry'))
await waitFor(() => rendered.getByText('error boundary'))
await waitFor(() => rendered.getByText('retry'))
succeed = true
fireEvent.click(rendered.getByText('retry'))
await waitFor(() => rendered.getByText('rendered'))

consoleMock.mockRestore()
})

it('should not call the queryFn when not enabled', async () => {
const key = queryKey()

Expand Down
15 changes: 11 additions & 4 deletions src/react/useBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@ import React from 'react'
import { useRerenderer } from './utils'
import { getResolvedQueryConfig } from '../core/config'
import { QueryObserver } from '../core/queryObserver'
import { QueryResultBase, QueryConfig, QueryKey } from '../core/types'
import { useQueryCache } from './ReactQueryCacheProvider'
import { QueryResultBase, QueryKey, QueryConfig } from '../core/types'
import { useErrorResetBoundary } from './ReactQueryErrorResetBoundary'
import { useQueryCache } from '.'
import { useContextConfig } from './ReactQueryConfigProvider'

export function useBaseQuery<TResult, TError>(
queryKey: QueryKey,
config?: QueryConfig<TResult, TError>
): QueryResultBase<TResult, TError> {
const rerender = useRerenderer()
const cache = useQueryCache()
const rerender = useRerenderer()
const contextConfig = useContextConfig()
const errorResetBoundary = useErrorResetBoundary()

// Get resolved config
const resolvedConfig = getResolvedQueryConfig(
Expand Down Expand Up @@ -49,7 +51,11 @@ export function useBaseQuery<TResult, TError>(
if (resolvedConfig.suspense || resolvedConfig.useErrorBoundary) {
const query = observer.getCurrentQuery()

if (result.isError && query.state.throwInErrorBoundary) {
if (
result.isError &&
!errorResetBoundary.isReset() &&
query.state.throwInErrorBoundary
) {
throw result.error
}

Expand All @@ -58,6 +64,7 @@ export function useBaseQuery<TResult, TError>(
resolvedConfig.suspense &&
!result.isSuccess
) {
errorResetBoundary.clearReset()
const unsubscribe = observer.subscribe()
throw observer.fetch().finally(unsubscribe)
}
Expand Down