Skip to content

Any plans on adding useFragment() hook and/or subscribing to a fragment change?Β #198

@dko-slapdash

Description

@dko-slapdash

Hi.

There is useQuery(), but there is no useFragment() which would allow to watch some fragment in the cache and re-render accordingly.

An example use-case would be the following:

const UserFragment = gql`
  fragment UserFragment on User {
    id
    name
  }
`;

const userFragment = gql`
  query User($id: ID!) {
    viewer {
      user(id: $id) {
        ...UserFragment
      }
    }
  }
  ${UserFragment}
`;

function MyComponent({ id }) {
  // If the user is already somewhere in the cache (most likely it is!),
  // return its data immediately.
  const { data } = useFragment(UserFragment, id);
  // In case the user is not in the cache yet, query it explicitly by ID
  // from some parametrized field.
  useQuery(userFragment, { id });
  // Render the user's name fetched by useFragment.
  return <div>{data?.name}</div>;
  // Next time if the user's name changes in the cache, useFragment will
  // trigger re-rendering again.
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions