-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
ApiProvider.tsx
55 lines (53 loc) · 1.56 KB
/
ApiProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { configureStore } from '@reduxjs/toolkit'
import type { Context } from 'react'
import React from 'react'
import type { ReactReduxContextValue } from 'react-redux'
import { Provider } from 'react-redux'
import { setupListeners } from '@reduxjs/toolkit/query'
import type { Api } from '@reduxjs/toolkit/dist/query/apiTypes'
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
export function ApiProvider<A extends Api<any, {}, any, any>>(props: {
children: any
api: A
setupListeners?: Parameters<typeof setupListeners>[1]
context?: Context<ReactReduxContextValue>
}) {
const [store] = React.useState(() =>
configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer,
},
middleware: (gDM) => gDM().concat(props.api.middleware),
})
)
// Adds the event listeners for online/offline/focus/etc
setupListeners(store.dispatch, props.setupListeners)
return (
<Provider store={store} context={props.context}>
{props.children}
</Provider>
)
}