-
Notifications
You must be signed in to change notification settings - Fork 7
Closed
Labels
πͺ react hooksFeature requests related to React hooksFeature requests related to React hooksproject-apollo-client (legacy)LEGACY TAG DO NOT USELEGACY TAG DO NOT USE
Description
Hi.
There is useQuery(), but there is no useFragment() which would allow to watch some fragment in the cache and re-render accordingly.
- This hook useFragment is supported in Relay: https://github.com/relay-tools/relay-hooks/blob/master/useFragment.md
- Some people implement work-arounds to achieve the same using hacks with client-only resolvers: https://github.com/abhiaiyer91/apollo-fragment
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.
}
OlegLustenko, tleunen, gaetansnl, hectahertz, jeongsd and 17 more
Metadata
Metadata
Assignees
Labels
πͺ react hooksFeature requests related to React hooksFeature requests related to React hooksproject-apollo-client (legacy)LEGACY TAG DO NOT USELEGACY TAG DO NOT USE