Documentation
Basics
Client

Client

TODO In-depth guide on client data fetching

Co-locate your fragments

When creating components it's useful to co-locate your data-requirements with your component, this way when you need more data for your component you know exactly where to add it and you don't have to go up your component-tree to find the query responsible for adding the data.

import { FragmentType, graphql, useFragment } from '@/gql'
import styles from './Avatar.module.css'
 
const UserFields = graphql(`
  fragment Avatar_UserFields on Launch {
    firstName
    avatarUrl
  }
`)
 
export const Avatar = (props: {
  user: FragmentType<typeof UserFields>
}) => {
  const user = useFragment(LaunchFields, props.user)
 
  return (
    <div styles={styles.avatar}>
      <img styles={styles.image} href={user.avatarUrl} alt="...">
      <span>Welcome, {user.firstName}</span>
    </div>
  )
}

The above defined fragment is now globally available and we can add it to our query:

const UserQuery = graphql(`
  query User ($id: ID!) {
    user(id: $id) {
      id
      ...Avatar_UserFields
    }
  }
`)

From now on out, every time we need a new field in the Avatar component we can just add it there and trust that the query is updated automatically and our data is passed into the component by menans of <Avatar user={result.data.user} />.