1 | import { configureStore } from '@reduxjs/toolkit'
|
2 | import type { Context } from 'react'
|
3 | import { useContext } from 'react'
|
4 | import { useEffect } from 'react'
|
5 | import React from 'react'
|
6 | import type { ReactReduxContextValue } from 'react-redux'
|
7 | import { Provider, ReactReduxContext } from 'react-redux'
|
8 | import { setupListeners } from '@reduxjs/toolkit/query'
|
9 | import type { Api } from '@reduxjs/toolkit/query'
|
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 | export function ApiProvider(props: {
|
36 | children: any
|
37 | api: Api<any, {}, any, any>
|
38 | setupListeners?: Parameters<typeof setupListeners>[1] | false
|
39 | context?: Context<ReactReduxContextValue | null>
|
40 | }) {
|
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 | }
|
48 | const [store] = React.useState(() =>
|
49 | configureStore({
|
50 | reducer: {
|
51 | [props.api.reducerPath]: props.api.reducer,
|
52 | },
|
53 | middleware: (gDM) => gDM().concat(props.api.middleware),
|
54 | }),
|
55 | )
|
56 |
|
57 | useEffect(
|
58 | (): undefined | (() => void) =>
|
59 | props.setupListeners === false
|
60 | ? undefined
|
61 | : setupListeners(store.dispatch, props.setupListeners),
|
62 | [props.setupListeners, store.dispatch],
|
63 | )
|
64 |
|
65 | return (
|
66 | <Provider store={store} context={context}>
|
67 | {props.children}
|
68 | </Provider>
|
69 | )
|
70 | }
|