I am in the process of creating a basic React component using apollo-client
alongside TypeScript.
This particular component is responsible for fetching a list of articles and displaying them. Here's the code:
import * as React from 'react';
import graphql from "react-apollo/graphql";
import { ARTICLES_FEED } from "../schemas/queries";
import { Article, ArticlesFeedResponse } from "../schemas/results";
import { ChildProps } from "react-apollo/types";
const AppQL = graphql<ArticlesFeedResponse, {}>(ARTICLES_FEED);
class App extends React.Component<ChildProps<{}, ArticlesFeedResponse>, {}> {
render() {
const { loading, feed, error } = this.props.data;
if (loading) return <div>loading</div>;
if (error) return <div>{ error }</div>;
return (
<React.Fragment>
<h1>It works!</h1>
{this.props.data && feed.map( (article:Article) => (
<div>{article.shortText}</div>
))}
</React.Fragment>
);
}
}
export default AppQL(App);
schemas/results:
export interface Article {
id: string,
shortText: string,
publicationDate: string
}
export type ArticlesFeedResponse = {
feed: Article[];
}
schemas/queries:
import gql from 'graphql-tag'
export const ARTICLES_FEED = gql`
query ArticlesFeed {
feed {
id
shortText
publicationDate
}
}
`;
Despite matching signatures, I encountered an error:
Type '(QueryProps<OperationVariables> & Partial<ArticlesFeedResponse>) | undefined' has no property 'loading' and no string index signature.
I seem to be confused - the imported types are:
ChildProps:
export declare type ChildProps<P, R> = P & {
data?: QueryProps & Partial<R>;
mutate?: MutationFunc<R>;
};
QueryProps:
export interface QueryProps<TVariables = OperationVariables> {
error?: ApolloError;
networkStatus: number;
loading: boolean;
variables: TVariables;
fetchMore: (fetchMoreOptions: FetchMoreQueryOptions & FetchMoreOptions) => Promise<ApolloQueryResult<any>>;
refetch: (variables?: TVariables) => Promise<ApolloQueryResult<any>>;
startPolling: (pollInterval: number) => void;
stopPolling: () => void;
subscribeToMore: (options: SubscribeToMoreOptions) => () => void;
updateQuery: (mapFn: (previousQueryResult: any, options: UpdateQueryOptions) => any) => void;
}
Therefore, ChildProps
should include both the loading
and error
properties. The inclusion of | undefined
in the union remains puzzling to me.
Any tips or advice?
P. S. When I refrain from importing the default ChildProps
from react-apollo/types
, and opt for this modified version instead:
type ChildProps<P, R> = P & {
data: QueryProps & R;
mutate?: MutationFunc<R>;
};
The code operates smoothly. I am left wondering - did I make a mistake, or could this be a bug within the react-apollo/types
package?