Mutation in nested components

With a complex UI, it happens quite often that a component which triggers a mutation is buried deep down a components tree. For now I have used the useMutation hook in the very same component which triggers the mutation. However, after a while of not developing a part of code, I find it really hard to remember which component contained the mutation.

Do you use any kind of convention with complex UIs in regards to where you put your useMutation hooks?

I am considering creating an intermediary component which would contain my “update” and “delete” mutations, which in turn would be called by callbacks passed to child components. However, before I spend some additional time on the refactoring, I would really appreciate to know if anyone else has implemented different approach and wanted to share their experience.

Just make global with all gql queries. This will achieve 2 things:

  1. All your query names will be unique
  2. You will have simple autocomplete on demand
  3. If you need to do some optimizations or changes, you have a single point to visit to make modifications to queries.

The reason you need to make sure all your query names are unique is to take full advantage of refetchQueries options. Something like this:

// Refetches two queries after mutation completes
const [addTodo, { data, loading, error }] = useMutation(repository.addToDo, {
  refetchQueries: [
    GET_POST, // DocumentNode object parsed with gql
    'GetPosts' // Query name
  ],
});

And there are 0 issues with having some repository imported where you need it.

If you want to be fancy you can create a hook that can handle communication with apollo so all you call are methods returned by hook.

To address this issue, one approach is to create an intermediary component that contains the mutations, as you mentioned. This can help centralize mutations in one place and make it easier to find them later on. You could pass callbacks to child components that trigger the mutations through props or context.

Another approach is to use a centralized state management library like Redux or Apollo Client to manage mutations. This can help simplify the codebase and make it easier to track mutations across the application.

Ultimately, the approach you choose will depend on your specific use case and the architecture of your application. It’s important to consider the tradeoffs of each approach and choose one that best fits your needs.