Querying for Users
Explore how to query user profiles in a React app using Apollo Client and GraphQL union types. Learn to generate TypeScript queries, differentiate user types like regular and suspended users, and implement typeguards for accurate data handling.
We'll cover the following...
A new page
In order to query for users, let’s create a brand new page within our application. We will create a new file at pages/users/[username].tsx for this. This page will be matched by an address such as http://*address_to_app*/users/radar12. Here is the code that we will put on this page:
import { useRouter } from "next/router";import { ApolloProvider } from "@apollo/client";import client from "client";import UserProfile from "components/Users/UserProfile";function User(){const router = useRouter();const { username } = router.query;return (<ApolloProvider client={client}><UserProfile username={username as string} /></ApolloProvider>);}export default User;
This page uses the useRouter hook from next/router to load the username from the route. The component then wraps another component called UserProfile in the same ApolloProvider and Layout component that we used in our pages/index.tsx file. The ApolloProvider component allows us to run GraphQL queries within the UserProfile component.
Let’s go ahead and create that new file for a component now. Rather than starting with a component this time, we’ll start with the GraphQL query and then use what that returns to inform the shape of our component. Let’s add the GraphQL query to a new file.
import gql from "graphql-tag";const userQuery = gql`query user($username: String!) {result: user(username: $username) {... on SuspendedUser {idusernamesuspensionReason}... on User {idusername}}}`;
Running GraphQL Code Generator with only the query present in our component's file generates the following src/generated/graphql.tsx file.
We can see that in lines 126–129, a new function called ...