Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Apollo useQuery hook with TypeScript

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

like image 925
Oleksandr Fomin Avatar asked Dec 23 '22 17:12

Oleksandr Fomin


1 Answers

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;
like image 138
Ivan Vasiljevic Avatar answered Jan 01 '23 08:01

Ivan Vasiljevic