react-apollo icon indicating copy to clipboard operation
react-apollo copied to clipboard

Mutation callbacks not called if component re-rendered immediately before calling mutation

Open leanne2 opened this issue 8 years ago • 4 comments

Intended outcome:

onCompleted or onError mutation callbacks always called

Actual outcome:

When using a mutation render props inside render(), onCompleted or onError mutation callbacks are not called and mutation data (e.g networkStatus etc) not updated if the component is re-rendered immediately before calling the mutation. This could be, for example, by calling setState immediately before calling the mutation

How to reproduce the issue:

Create a react component with a method callMuation() In render() include a mutation render prop, Include a button whose onClick handler, when called calls this.callMutation, passing the the mutation render prop method as an argument to this.callMuation In this.callMutation, call this.setState() or this.forceUpdate() to trigger a re-render then immediately call the mutation prop function. In this scenario, the mutation fires and any update methods are fired, but onCompleted or onError do no get called. Also the mutation data does not get updated e.g. loading and error render props

Version

leanne2 avatar Oct 25 '18 10:10 leanne2

I just ran into this issue also, my solution was to make the onClick handler asynchronous and then wait for the mutation function.

class foo extends React.Component {
  
  state = {
    bar:false
  }  

  handleClick = async (mutationFn:MutationFn) => () => {
      await mutationFn(...variables)
      this.setState({bar:true})
  }    

  render () {
        ... Button here somewhere ...
       <Button onClick={this.handleClick(mutationFn)}/>
  }

}

Hope this helps. Definitely not expected behavior from the client.

Rkuro avatar Dec 15 '18 19:12 Rkuro

@Rkuro Thanks for your workaround. Another (heavier-duty) option is to pull the Mutation into a container parent component that renders the component with the button as a child, so that the container component does get not re-rendered by the child component's state change. But agree neither solution should be needed.

leanne2 avatar Dec 17 '18 09:12 leanne2

We cannot control or change the react component lifecycle or control a parent's rerendering. Therefore, I don't think there is any action we can take here. If I am mistaken and there is something actionable that can be done please ping me and I will reopen.

rosskevin avatar Dec 28 '18 02:12 rosskevin

Hi @rosskevin i have the same problem too. Here is my code:

https://gist.github.com/dafapramudya/98684603c3c465713f9c26858655ab62

So the problem is in ternary condition. When mutation is success, it will update data.topup.Status, and then onCompleted doesn't run because data.topup.Status is changed.

Can u help me pls? Thank you

dapapkung avatar Mar 21 '19 05:03 dapapkung