0

Many examples of how to Apollo involve something like

<Mutation
     mutation={YOUR_MUTATION}
     update={(cache, { data }) => {
         // do stuff to update Apollo store
     }}
 >
   { mutate => ( <UI mutate={mutate} /> ) }

  </Mutation>

These two rules conflict in ESLint rules and also in practice. We also know that JSX props should not use .bind() - how to avoid using bind? JSX props instantiating new arrow functions on each render aren't good practice.

  1. How/where do you write your update handlers?
  2. If the goal is to make as many "pure" functions as possible, what's the right way to attach a handler to the update prop?
Anthony Chung
  • 1,467
  • 2
  • 22
  • 44
  • The answer you mentioned is suggesting a solution already - to use class methods (e.g. bind in a constructor or better arrow functions as class properties) – amankkg Jun 14 '18 at 16:58

2 Answers2

0

Create an update function in the component that's calling the Mutation component. Like so:

class Root extends React.Component {
  update = (cache, { data }) => {
    // do stuff to update Apollo store
  };

  render() {
    return (
      <Mutation
        mutation={YOUR_MUTATION}
       update={this.update}
      >
        {mutate => (<UI mutate={mutate} />)}
      </Mutation>
    )
  }
}

This way, you're not creating a new function every render, only when the Root component is mounted.

EDIT:

If the update is a pure function, you can put it outside of the class declaration altogether.

Sergio Moura
  • 4,888
  • 1
  • 21
  • 38
0

The problem here is new handler every component re-render which can affect performance and lead to cascading re-renders of children.

I think you should use one of the following approche:

1) Extract you function to module global const if don't need class context inside

const handler = () => {//asdfasdf}
const component = () => {
  return <Mutation
     mutation={YOUR_MUTATION}
     update={handler}
 >
   { handler ) }

  </Mutation>
}

2) Class with arrow propertirs

class Component extends React.Component {
  update = (u) => this.props.update;
  render () {
    return <Mutation
     mutation={YOUR_MUTATION}
     update={this.update}
 >
   { etc... }

  </Mutation>
  }
}