-
-
Save danieldogeanu/cb114964d3d5a59127c4c7f3c03d4dd1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ComponentProps, FC, Fragment } from "react"; | |
export interface ProvidersProps { | |
children: React.ReactNode; | |
} | |
export type ProviderWithProps = [FC<ProvidersProps>, Object]; | |
/** | |
* Function that combines all the context providers into a single one. | |
* @param providers Array of tuples with Provider and props pairs. | |
* @returns Returns the combined providers. | |
*/ | |
export function combineProviders(providers: ProviderWithProps[]): FC<ProvidersProps> { | |
// We need to use regular named functions, and not arrow functions because otherwise | |
// ESLint will scream at us that the "Component definition is missing display name (react/display-name)". | |
function reducer(CombinedProviders: FC<ProvidersProps>, [CurrentProvider, props = {}]: ProviderWithProps) { | |
return function combiner({children}: ComponentProps<FC<ProvidersProps>>): JSX.Element { | |
return <CombinedProviders><CurrentProvider {...props}>{children}</CurrentProvider></CombinedProviders>; | |
}; | |
} | |
// We also need to provide an initial value for the reducer. | |
function initialValue({children}: ComponentProps<FC<ProvidersProps>>): JSX.Element { | |
return <Fragment>{children}</Fragment>; | |
} | |
return providers.reduce(reducer, initialValue); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BrowserRouter } from "react-router-dom"; | |
import { RecoilRoot } from "recoil"; | |
import { ApolloProvider } from "@apollo/client"; | |
import { combineProviders } from "./combine-provider"; | |
const Providers = combineProviders([ | |
[BrowserRouter, { basename: 'optionalString', forceRefresh: true }], | |
[RecoilRoot, { initializeState: (MutableSnapshot => void), override: false }], | |
[ApolloProvider, { client } ], | |
]); | |
function Root() { | |
return ( | |
<Providers> | |
<App /> | |
</Providers> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment