javascriptreactjsreact-router-dom

How to redirect after successful login in react js


I am using building a react app Here I am unable to figure out how to redirect to /dashboard after successfull login. Any help would be usefull

In this file i am passing my username and password to my redux action this.props.login

signin.js

    handleLoginClick = () => {
        const { inputUserID, inputPassword } = this.state;

        this.login(inputUserID, inputPassword)

      };
    login = (username, password) => {
        this.props.login(username, password);

      };



  render() {
    const {
      showError,
      open,
      inputUserID,
      inputPassword,
      checkRememberID,
      showPhoneNumberDialog,
      showVerifyNumberDialog
    } = this.state;


    return (
      <div className="sign-in-dialog-container">

        <Dialog
          id="dialog-sign-in"
          className="dialog"
          open={open}
          onClose={this.handleClose}
          aria-labelledby="form-dialog-title"
          style={{

            backgroundColor: '#fff'
          }}
        >
          <DialogTitle id="form-dialog-title">Sign In</DialogTitle>
          <DialogContent className="dialog-content">
            <div className="dialog-content-form">
              <div className="form-field">
                <div className="content-label">ID</div>
                <FormControl fullWidth variant="outlined">
                  <OutlinedInput
                    fullWidth
                    type="text"
                    placeholder="User Name"
                    value={inputUserID}
                    onChange={this.handleTextChange("inputUserID")}
                    labelWidth={0}
                  />
                </FormControl>
              </div>

              <div className="form-field margin-top-16">
                <div className="content-label">Password</div>
                <FormControl fullWidth variant="outlined">
                  <OutlinedInput
                    fullWidth
                    type="password"
                    placeholder="**********"
                    value={inputPassword}
                    onChange={this.handleTextChange("inputPassword")}
                    labelWidth={0}
                  />
                  {showError ? (
                    <FormHelperText className="password-incorrect-text">
                      Password is incorrect
                    </FormHelperText>
                  ) : null}
                </FormControl>
              </div>

              <div className="form-field">
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={checkRememberID}
                      onChange={this.handleCheckboxChange("checkRememberID")}
                      value="checkRememberID"
                      color="primary"
                    />
                  }
                  label="Remember ID"
                />
              </div>

              <div className="form-field">
                <Button
                  className="next-button custom-button-style"
                  fullWidth
                  onClick={this.handleLoginClick}
                  variant="contained"
                  color="primary"
                >
                  Next
                  </Button>
              </div>


            </div>
          </DialogContent>

          <div className="bottom-row">
            <span className="helper-text">
              Don't have an account?
                <span
                onClick={this.handleSignUpClick}
                className="strong cursor-pointer"
              >
                {" "}
                  Sign Up
                </span>
            </span>
          </div>
        </Dialog>
      </div>
    );
  }

}

const mapStateToProps = state => ({
  user: state.userReducer,
  productPageReducer: state.productPageReducer,
  isAuthenticated: state.auth.access_token,
});

const mapDispatchToProps = {
  getProductList,
  login,
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SignIn);

authAction.js

export const login = (username, password) => (dispatch) => {
    //User Loading:
    dispatch({ type: USER_LOADING });
    //Make API Call here
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "Basic dG9wc2VsbGVyOnRvcHNlbGxlcg==");

    var formdata = new FormData();
    formdata.append("username", username);
    formdata.append("password", password);
    formdata.append("grant_type", "password");

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: formdata,
        redirect: 'follow'
    };

    fetch("https://api.XXXXXXXXXXXXX.com/oauth/token", requestOptions)
        .then(response => response.json())
        .then(
            res => {
                if (res.access_token && res.refresh_token) {
                    window.localStorage.access_token = res.access_token;
                    window.localStorage.refresh_token = res.refresh_token;
                    dispatch({
                        type: LOGIN_SUCCESS,
                        user: res
                    });
                } else {
                    dispatch({
                        type: LOGIN_FAIL,
                        message: 'Unauthorised User'
                    })
                }

            }
        )
        .catch(error =>
            dispatch({
                type: LOGIN_FAIL,
                message: error
            })
        );

}

Here i want to figure out how to redirect to /dashboard after successfull login.I am also using react-router-dom.


Solution

  • It seems like after successful sign-in attempt, { user } state at your redux store change.

    therefore you might consider add this at signin.js


              import {Redirect } from 'react-router-dom';  
    
              class SignIn extends Component { 
              ...rest class..
              render ()
              const { user } = this.props;
              return( 
              <>
               { if (user)<Redirect to="/dashboard" />;} // in case { user } is null at initial state, otherewise change the checker... 
              ...rest code...
              </>
              )
    }
    

    working example - https://github.com/zero-to-mastery/visual-music/blob/development/src/pages/Login/Login.js