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.
}
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.
Most helpful comment
I think this would be really useful to help with data masking