railbird-gql/component/with-query-handling.tsx

43 lines
1.4 KiB
TypeScript

import React from "react";
import { useQuery, DocumentNode, OperationVariables } from "@apollo/client";
import { Text } from "react-native";
/**
* A higher-order component that provides loading and error handling for GraphQL queries.
* @param {React.ComponentType} WrappedComponent - The component to wrap.
* @param {DocumentNode} query - The GraphQL query to execute.
* @param {string} dataKey - The key in the data object to pass to the wrapped component.
* @param {Object} queryOptions - Optional. Additional options for the Apollo query.
* @returns {React.ComponentType} A component that renders the WrappedComponent with loading and error handling.
*/
/* eslint-disable react/display-name */
type WithQueryHandlingProps = {
WrappedComponent: React.ComponentType<any>;
query: DocumentNode;
dataKey: string;
queryOptions?: OperationVariables;
};
function withQueryHandling({
WrappedComponent,
query,
dataKey,
queryOptions = {},
}: WithQueryHandlingProps) {
return function (props: any) {
// You can replace 'any' with specific props type if known
const { loading, error, data } = useQuery(query, queryOptions);
if (loading) {
return <Text>Loading...</Text>;
}
if (error) {
return <Text>Error: {error.message}</Text>;
}
const specificData = data[dataKey];
return <WrappedComponent {...props} data={specificData} />;
};
}
export default withQueryHandling;