Apollo-feature-requests: Any plans on adding useFragment() hook and/or subscribing to a fragment change?

Created on 15 Dec 2019  路  3Comments  路  Source: apollographql/apollo-feature-requests

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.
}

Most helpful comment

I think this would be really useful to help with data masking

All 3 comments

I think this would be really useful to help with data masking

could this be the same as (rough code):

const useFragment = (fragment, id) => useApolloClient().readFragment({ id, fragment })

?

@rajington it's close except readFragment doesn't return an Observable so the result won't update when the store data changes.

Was this page helpful?
0 / 5 - 0 ratings