Skip to content

Instantly share code, notes, and snippets.

@hyochan
Created July 17, 2021 03:17
Show Gist options
  • Save hyochan/7ea10143fbba62c3205bf8d59e6461a8 to your computer and use it in GitHub Desktop.
Save hyochan/7ea10143fbba62c3205bf8d59e6461a8 to your computer and use it in GitHub Desktop.
Resettable relay provider will let you fully reset the cache of the relay client. Useful when you want to clear cache when user sign out.
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 {
/**
* Factory function for generating Relay environments.
*/
createRelayEnvironment: () => IEnvironment;
}
const [useResettableRelayContext, Provider] = createCtx<Context>();
const ResettableRelayProvider: FC<Props> = ({
children,
createRelayEnvironment,
}) => {
const [environment, setEnvironment] = useState<IEnvironment>(
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