Skip to content

Instantly share code, notes, and snippets.

@codyromano
Last active April 21, 2020 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyromano/fba0c95abfc53c48cba98288d7226ab4 to your computer and use it in GitHub Desktop.
Save codyromano/fba0c95abfc53c48cba98288d7226ab4 to your computer and use it in GitHub Desktop.
// Options available when creating the HOC
export type WithFocusQueryOptions<ComponentProps, QueryVars> = {
query: DocumentNode;
getQueryVars?: (props: ComponentProps) => QueryVars;
};
// Props provided to the wrapped component
export type WithFocusQueryProps<QueryResponse, QueryVars> = {
data: QueryResponse;
refetch: (options?: QueryVars) => void;
};
export default function withFocusQuery<ComponentProps, QueryResponse = null, QueryVars = null>({
query,
getQueryVars,
}: WithFocusQueryOptions<ComponentProps, QueryVars>
) {
return (Component: React.ComponentType<
ComponentProps & WithFocusQueryProps<QueryResponse, QueryVars>
>) => (props: ComponentProps) => {
const [getData, { data, loading, error }] = useLazyQuery<QueryResponse, QueryVars>(query);
const checkForData = useCallback(() => {
const queryVars = getQueryVars ? getQueryVars(props) : null;
getData(queryVars);
}, [data, error, loading])
useFocusEffect(checkForData);
if (!data) {
return (
<SafeAreaView>
{loading ? <Spinner /> : null}
{error ? <Text status="error">Sorry, there was a fetch error.</Text> : null}
</SafeAreaView>
)
}
return (
<Component
{...props}
data={data}
refetch={getData}
/>
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment