How to run a mutation on mount with React Apollo 2.1's Mutation component?
Right or wrong, Apollo makes some assumptions about how queries and mutations are used. By convention queries only fetch data while mutations, well, mutate data. Apollo takes that paradigm one step further and assumes that mutations will happen in response to some sort of action. So, like you observed, Query
fetches the query on mount, while Mutation
passes down a function to actually fetch the mutation.
In that sense, you've already deviated from how these components are "supposed to be used."
I don't think there's anything outright wrong with your approach -- assuming called
never gets reset, your component should behave as intended. As an alternative, however, you could create a simple wrapper component to take advantage of componentDidMount
:
class CallLogin extends React.Component {
componentDidMount() {
this.props.login()
}
render() {
// React 16
return this.props.children
// Old School :)
// return <div>{ this.props.children }</div>
}
}
export default function Authenticator({ apiKey, render }) {
return (
<Mutation mutation={AUTH_MUTATION} variables={{ apiKey }}>
{(login, { data, error }) => {
const token = (data && data.login.token) || undefined;
return (
<CallLogin login={login}>
{render({ error, token })}
</CallLogin>
)
}}
</Mutation>
);
}