Created
May 15, 2021 07:41
-
-
Save hyochan/3ebadb2177c6471f760121a835d893f1 to your computer and use it in GitHub Desktop.
ResettableRelayProvider.tsx
This file contains 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 React, {FC, useState} from 'react'; | |
import {IEnvironment} from 'relay-runtime'; | |
import {RelayEnvironmentProvider} from 'react-relay/hooks'; | |
import createCtx from '../utils/createCtx'; | |
interface Context { | |
/** | |
* Current Relay environment. | |
*/ | |
environment: IEnvironment; | |
/** | |
* Discard the current Relay environment and | |
* create a new one. | |
*/ | |
resetRelayEnvironment: () => void; | |
} | |
interface Props { | |
/* For testing */ | |
environment?: IEnvironment; | |
/* Factory function for generating Relay environments */ | |
createRelayEnvironment: () => IEnvironment; | |
} | |
const [useResettableRelayContext, Provider] = createCtx<Context>(); | |
const ResettableRelayProvider: FC<Props> = ({ | |
children, | |
environment: initialEnvironment, | |
createRelayEnvironment, | |
}) => { | |
const [environment, setEnvironment] = useState<IEnvironment>( | |
initialEnvironment || createRelayEnvironment(), | |
); | |
const resetRelayEnvironment = (): void => { | |
setEnvironment(createRelayEnvironment()); | |
}; | |
return ( | |
<Provider value={{environment, resetRelayEnvironment}}> | |
<RelayEnvironmentProvider environment={environment}> | |
{children} | |
</RelayEnvironmentProvider> | |
</Provider> | |
); | |
}; | |
export {useResettableRelayContext, ResettableRelayProvider}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment