Nicolas S.Xu
Nicolas S.Xu

Reputation: 14524

I need to update state in render() function in reactjs. How?

What are the solutions for this problem?

<Form.Field>
  <label>&nbsp;</label>
  <MockMutation mutation={DO_LOGIN}>
    {(doLogin, { loading, error, data }) => {
      if (!loading && data.loggedInState == "LOGGED_IN") {
        // this.setState({goodLogin: true})
        // I need to update state here to redirect to other page
        // How can I do it with out the annoying warning???
      }
      return (
        <Button
          primary
          className="login-btn full-width"
          disabled={loading}
          onClick={e => {
            console.log("on click btn clicked");
            e.preventDefault();
            doLogin({
              variables: {
                employeeId: this.state.employeeId,
                password: this.state.password
              }
            });
          }}
        >
          <span style={loading ? { display: "none" } : {}}>Login</span>
          <span style={loading ? {} : { display: "none" }}>Loading...</span>
        </Button>
      );
    }}
  </MockMutation>
</Form.Field>

Upvotes: 0

Views: 38

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

If you are using react-router.v4 you can use Redirect component to do make a redirect.

if (!loading && data.loggedInState == "LOGGED_IN") {
  // this.setState({goodLogin: true})
  // I need to update state here to redirect to other page
  // How can I do it with out the annoying warning???
  return <Redirect to="/some/path" />
}

If you don't use react-router-4 then it is fairly easy to implement such component anyway:

class Redirect extends React.Component {
  componentDidMount(){
    const { history, to } = this.props;
    history.push(to);
  }

  render() {
    return null
  }
}

export default withRouter(Redirect);

Upvotes: 1

Related Questions