0
votes

So I have the following code using Apollo Graphql, The component will re-render everytime that I click the button which will trigger an onClick event. If I add some state changes after the then call in the mutation function, the component will basically re-render twice, one for mutation re-render and one for the other state change re-render and it will create a visual flash on the page.

How do I stop useMutation from re-rendering the page?

import { useMutation, gql } from '@apollo/client';;
import React from 'react';

const ADD_TAGS = gql`
mutation($ids: [ID!]!) {
  addTags(ids: $ids) {
    id
  }
}
`;

export default () => {
  const [addTags] = useMutation(ADD_TAGS, {
    onCompleted: () => {console.log('on complete')}
  });
  console.log('render');
  return <div>
    This is a test idPages
    <button onClick={() => addTags({
      variables: {
        ids: ['123']
      }
    }).then(data => console.log('finished', data))}>Add</Button>
  </div>
}
1
are you sure? what was logged? ... rerenders are for loading state, new data... nothing to fightxadm

1 Answers

0
votes

According to useMutation and MutationData implementation if the previous result is different from the current result it will causes an state updates :

private updateResult(result: MutationResultWithoutClient<TData>) {
    if (
      this.isMounted &&
      (!this.previousResult || !equal(this.previousResult, result))
    ) {
      this.setResult(result);
      this.previousResult = result;
    }
 }

For some reason every time you call addTags it detects that the current result is different from the prevoius one.