Skip to content

Commit f3fd32f

Browse files
author
ben.durrant
committed
Throw an error if ApiProvider is nested inside a normal Provider.
1 parent 759581f commit f3fd32f

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

packages/toolkit/src/query/react/ApiProvider.tsx

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { configureStore } from '@reduxjs/toolkit'
22
import type { Context } from 'react'
3+
import { useContext } from 'react'
34
import { useEffect } from 'react'
45
import React from 'react'
56
import type { ReactReduxContextValue } from 'react-redux'
6-
import { Provider } from 'react-redux'
7+
import { Provider, ReactReduxContext } from 'react-redux'
78
import { setupListeners } from '@reduxjs/toolkit/query'
89
import type { Api } from '@reduxjs/toolkit/query'
910

@@ -37,6 +38,13 @@ export function ApiProvider<A extends Api<any, {}, any, any>>(props: {
3738
setupListeners?: Parameters<typeof setupListeners>[1] | false
3839
context?: Context<ReactReduxContextValue>
3940
}) {
41+
const context = props.context || ReactReduxContext
42+
const existingContext = useContext(context)
43+
if (existingContext) {
44+
throw new Error(
45+
'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.'
46+
)
47+
}
4048
const [store] = React.useState(() =>
4149
configureStore({
4250
reducer: {
@@ -55,7 +63,7 @@ export function ApiProvider<A extends Api<any, {}, any, any>>(props: {
5563
)
5664

5765
return (
58-
<Provider store={store} context={props.context}>
66+
<Provider store={store} context={context}>
5967
{props.children}
6068
</Provider>
6169
)

packages/toolkit/src/query/tests/apiProvider.test.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import * as React from 'react'
22
import { createApi, ApiProvider } from '@reduxjs/toolkit/query/react'
33
import { fireEvent, render, waitFor } from '@testing-library/react'
44
import { waitMs } from './helpers'
5+
import { Provider } from 'react-redux'
6+
import { configureStore } from '@reduxjs/toolkit'
57

68
const api = createApi({
79
baseQuery: async (arg: any) => {
@@ -57,4 +59,15 @@ describe('ApiProvider', () => {
5759
// Being that nothing has changed in the args, this should never fire.
5860
expect(getByTestId('isFetching').textContent).toBe('false')
5961
})
62+
test('ApiProvider throws if nested inside a Redux context', () => {
63+
expect(() =>
64+
render(
65+
<Provider store={configureStore({ reducer: () => null })}>
66+
<ApiProvider api={api}>child</ApiProvider>
67+
</Provider>
68+
)
69+
).toThrowErrorMatchingInlineSnapshot(
70+
'"Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup."'
71+
)
72+
})
6073
})

0 commit comments

Comments
 (0)