Last active
April 21, 2020 03:36
-
-
Save codyromano/fba0c95abfc53c48cba98288d7226ab4 to your computer and use it in GitHub Desktop.
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
// 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