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

Override unwrap behavior for buildInitiateQuery, update tests #1786

Merged
merged 6 commits into from
Dec 8, 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
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ jobs:
fail-fast: false
matrix:
node: ['14.x']
ts: ['3.9', '4.0', '4.1', '4.2', '4.3', 'next']
ts: ['3.9', '4.0', '4.1', '4.2', '4.3', , '4.4', '4.5', 'next']
steps:
- name: Checkout repo
uses: actions/checkout@v2
Expand Down
14 changes: 12 additions & 2 deletions packages/toolkit/src/query/core/buildInitiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,9 @@ Features like automatic cache collection, automatic refetching etc. will not be
})
const thunkResult = dispatch(thunk)
middlewareWarning(getState)
const { requestId, abort, unwrap } = thunkResult

const { requestId, abort } = thunkResult

const statePromise: QueryActionCreatorResult<any> = Object.assign(
Promise.all([runningQueries[queryCacheKey], thunkResult]).then(() =>
(api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(
Expand All @@ -289,7 +291,15 @@ Features like automatic cache collection, automatic refetching etc. will not be
subscriptionOptions,
queryCacheKey,
abort,
unwrap,
async unwrap() {
const result = await statePromise

if (result.isError) {
throw result.error
}

return result.data
},
refetch() {
dispatch(
queryAction(arg, { subscribe: false, forceRefetch: true })
Expand Down
3 changes: 2 additions & 1 deletion packages/toolkit/src/query/react/buildHooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AnyAction, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit'
import { createSelector, Selector } from '@reduxjs/toolkit'
import { createSelector } from '@reduxjs/toolkit'
import type { Selector } from '@reduxjs/toolkit'
import type { DependencyList } from 'react'
import {
useCallback,
Expand Down
112 changes: 112 additions & 0 deletions packages/toolkit/src/query/tests/buildHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ const api = createApi({
body: { name: 'Timmy' },
}),
}),
getUserAndForceError: build.query<{ name: string }, number>({
query: () => ({
body: {
forceError: true,
},
}),
}),
getIncrementedAmount: build.query<any, void>({
query: () => ({
url: '',
Expand Down Expand Up @@ -915,6 +922,111 @@ describe('hooks tests', () => {
expect(screen.queryByText(/An error has occurred/i)).toBeNull()
expect(screen.queryByText('Request was aborted')).toBeNull()
})

test('unwrapping the useLazyQuery trigger result does not throw on ConditionError and instead returns the aggregate error', async () => {
function User() {
const [getUser, { data, error }] =
api.endpoints.getUserAndForceError.useLazyQuery()

const [unwrappedError, setUnwrappedError] = React.useState<any>()

const handleClick = async () => {
const res = getUser(1)

try {
await res.unwrap()
} catch (error) {
setUnwrappedError(error)
}
}

return (
<div>
<button onClick={handleClick}>Fetch User</button>
<div data-testid="result">{JSON.stringify(data)}</div>
<div data-testid="error">{JSON.stringify(error)}</div>
<div data-testid="unwrappedError">
{JSON.stringify(unwrappedError)}
</div>
</div>
)
}

render(<User />, { wrapper: storeRef.wrapper })

const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
fireEvent.click(fetchButton)
fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real error to resolve.

await waitFor(() => {
const errorResult = screen.getByTestId('error')?.textContent
const unwrappedErrorResult =
screen.getByTestId('unwrappedError')?.textContent

errorResult &&
unwrappedErrorResult &&
expect(JSON.parse(errorResult)).toMatchObject({
status: 500,
data: null,
}) &&
expect(JSON.parse(unwrappedErrorResult)).toMatchObject(
JSON.parse(errorResult)
)
})

expect(screen.getByTestId('result').textContent).toBe('')
})

test('useLazyQuery does not throw on ConditionError and instead returns the aggregate result', async () => {
function User() {
const [getUser, { data, error }] = api.endpoints.getUser.useLazyQuery()

const [unwrappedResult, setUnwrappedResult] = React.useState<
undefined | { name: string }
>()

const handleClick = async () => {
const res = getUser(1)

const result = await res.unwrap()
setUnwrappedResult(result)
}

return (
<div>
<button onClick={handleClick}>Fetch User</button>
<div data-testid="result">{JSON.stringify(data)}</div>
<div data-testid="error">{JSON.stringify(error)}</div>
<div data-testid="unwrappedResult">
{JSON.stringify(unwrappedResult)}
</div>
</div>
)
}

render(<User />, { wrapper: storeRef.wrapper })

const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
fireEvent.click(fetchButton)
fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real result to resolve and ignore the error.

await waitFor(() => {
const dataResult = screen.getByTestId('error')?.textContent

Choose a reason for hiding this comment

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

should be

const dataResult = screen.getByTestId('result')?.textContent

const unwrappedDataResult =
screen.getByTestId('unwrappedResult')?.textContent

dataResult &&
unwrappedDataResult &&
expect(JSON.parse(dataResult)).toMatchObject({
name: 'Timmy',
}) &&
expect(JSON.parse(unwrappedDataResult)).toMatchObject(
JSON.parse(dataResult)
)
})

expect(screen.getByTestId('error').textContent).toBe('')
})
})

describe('useMutation', () => {
Expand Down