Invariant Violation setting state in Apollo mutate callback

本小妞迷上赌 提交于 2019-12-25 05:19:09

问题


I'm calling a mutate function from an event handler and getting an Invariant Violation error when I try to use this.setState in the catch clause.

saveToken({data}){
  let {userId, token, expires} = data.login;
  storeLoginToken(userId, token, expires);
  history.push('/dogs');
}
setErrors(error){
  this.setState('error', error.graphQLErrors);
}
handleSubmit(event) {
  event.preventDefault();
  let {email, password} = this.state;
  let {history} = this.props;
  let clientKey = getClientKey();
  this.props.mutate({ variables: { email, password, clientKey } })
    .then(this.saveToken.bind(this))
    .catch(this.setErrors.bind(this))
}

回答1:


I think the problem is that you missed the opening and closing brackets inside the setState function.

I would write it like this:

class ClassName extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        error,
        ...
      };
      
      this.saveToken = this.saveToken.bind(this);
      this.setErrors = this.setErrors.bind(this)
    }

    ...

    setErrors(error) {
      this.setState({error: error.graphQLErrors}); // should work with brackets
    }
    
  handleSubmit(event) {
    event.preventDefault();
    let { email, password } = this.state;
    let { history } = this.props;
    let clientKey = getClientKey();
    this.props.mutate({
        variables: {
          email,
          password,
          clientKey
        }
      })
      .then(this.saveToken)
      .catch(this.setErrors)
  }

}


来源:https://stackoverflow.com/questions/43011694/invariant-violation-setting-state-in-apollo-mutate-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!