Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
Custom useMutation hook with Apollo Client and React

When using Apollo client, I find it quite tedious to manually update the cache for every mutation that requires an immediate UI update. I therefore decided to try to make a custom hook which updates the cache automatically.

The hook works but it seems a little "hacky" and I'm worried it might mess with the normal functioning of the cache. So I just wanted to ask if this hook seems like it should work ok?

Here's the code (where mutationName is the actual graphql mutation name and fieldName is the original graphql query name corresponding to the mutation):

export const useMutationWithCacheUpdate = (
  mutation,
  mutationName,
  fieldName
) => {
  const [createMutation, { data, loading, error }] = useMutation(mutation, {
    update(cache, { data }) {
      data = data[mutationName];
      cache.modify({
        fields: {
          [fieldName]: (existingItems = []) => {
            const newItemRef = cache.writeFragment({
              data: data,
              fragment: gql`
                  fragment newItem on ${fieldName} {
                    id
                    type
                  }
                `,
            });
            return [...existingItems, newItemRef];
          },
        },
      });
    },
  });
  return [createMutation, { data, loading, error }];
};
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!