I'm trying to get useQuery
hook to work with TypeScript.
Here is my query
export const FETCH_LINKS = gql`
query FetchLinks {
feed {
links {
id
createdAt
url
description
}
}
}
`;
I generated the types from GraphQL schema with graphql-codegen
export type Feed = {
__typename?: 'Feed';
links: Array<Link>;
count: Scalars['Int'];
};
export type Link = {
__typename?: 'Link';
id: Scalars['ID'];
createdAt: Scalars['DateTime'];
description: Scalars['String'];
url: Scalars['String'];
postedBy?: Maybe<User>;
votes: Array<Vote>;
};
In my component, I apply the type to useQuery
hook
const { data, loading, error } = useQuery<Feed>(FETCH_LINKS);
The problem is that in the data
variable I receive an object of the following shape:
{
feed: {
__typename
links
count
}
}
So, in order to loop through the array of links and render them on the page, I need to do data.feed.links.map()
but the Feed
type does not have a feed
property on it and therefore, I get an error message Property 'feed' does not exist on type 'Feed'
How do I rectify this inconsistency
If you check documentation you will see that you would need to create one more interface to represent data:
interface FetchLinksData {
feed: Feed[];
}
In component you could use that like this:
const { data, loading, error } = useQuery<FetchLinksData>(FETCH_LINKS);
const feeds = data.feed;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With