Abdul Rauf
Abdul Rauf

Reputation: 100

How can I get my component to redirect after successful action?

I am working on a sign up page and i want my user to redirect to different component after successful signup i am using redux to manage the state of the application i want my user to only go to that certain page after successful sign up. The problem is i dont know where to call it after successful action

My component


class Signup  extends Component {

    constructor(props) {
     super(props);
     this.state = {
        user: {
            name: '',
            surname: '',
            emailAddress: '',
            userName: '',
            password: '',
            reEnterPassword: '',
            isActive: true,

        },
        submitted: false,
        error: ''
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}


    handleChange(event) {
        const { name, value } = event.target;
        const { user } = this.state;
        this.setState({
            user: {
                ...user,
                [name]: value
            }
        });
    } 

    async handleSubmit(event) {
        event.preventDefault();

        this.setState({ submitted: true });
        const { user } = this.state;
        await store.dispatch(Register.Create(user))
        this.props.history.push('/continue')

    }


    validateEmail = emailAddress => {
        var re = /\S+@\S+\.\S+/;
        return re.test(emailAddress) && <div className="help-block">Invalid emailAddress</div>;
    };
    render() {
        const { user, submitted } = this.state; 
        return (
            <div id="wrapper" class="signup">
        <div class="signup-holder">
            <div class="container">
                <div class="row">
                    <div class="col">
                        <div class="img-bx" style={{backgroundImage: "url(images/img01.jpg)"}}>
                        </div>
                    </div>
                    <div class="col">
                        <form class="form"  onSubmit={this.handleSubmit}>
                            <div class="logo">
                                <a href="#">
                                    <img src="images/logo.png"/>
                                </a>
                            </div>
                            <div class={'form-group' + (submitted && !user.name ? ' has-error' : '')} >
                                <label class="form-label">First Name</label>
                                <input type="text" class="form-control" name = "name" value={user.name} onChange={this.handleChange} />
                        {submitted && !user.name &&
                            <div className="help-block">First Name is Required</div>
                        }
                            </div>
                            <div class={'form-group' + (submitted && !user.surname ? ' has-error' : '')} >
                                <label class="form-label">Last Name</label>
                                <input type="text" class="form-control" name = "surname" value={user.surname} onChange={this.handleChange} />
                        {submitted && !user.surname &&
                            <div className="help-block">Last Name is Required</div>
                        }
                            </div>
                            <div class={'form-group' + (submitted && !user.userName ? ' has-error' : '')} >
                                <label class="form-label">UserName</label>
                                <input type="text" class="form-control" name = "userName" value={user.userName} onChange={this.handleChange} />
                        {submitted && !user.userName &&
                            <div className="help-block">userName is Required</div>
                        }
                            </div>
                            <div class={'form-group' + (submitted && !user.emailAddress ? ' has-error' : '')}>
                                <label class="form-label">Email</label>
                                <input type="emailAddress" class="form-control" name="emailAddress" value={user.emailAddress} onChange={this.handleChange} />
                        {submitted && !user.emailAddress &&
                            <div className="help-block">emailAddress is Required</div>  

                        }
                            </div>
                            <div class={'form-group' + (submitted && !user.password ? ' has-error' : '')}>
                                <label class="form-label">Password</label>
                                <input type="password" class="form-control" name= "password" value={user.password} onChange={this.handleChange} />
                        {submitted && !user.password &&
                            <div className="help-block">Password is Required</div>
                        }
                            </div>
                            <div class={'form-group' + (submitted && !user.reEnterPassword ? ' has-error' : '')}>
                                <label class="form-label">Re-Enter Password</label>
                                <input type="password" class="form-control" name="reEnterPassword"  value={user.reEnterPassword} onChange={this.handleChange} />
                        {submitted && !user.reEnterPassword && 
                            <div className="help-block">Password is Required</div> || user.password != user.reEnterPassword &&
                            <div className="help-block">Password doesnot match</div>
                        }
                            </div>

                            <div class="form-group clearfix">
                                <div class="pull-left">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="customCheck" name="isActive" value={user.isActive} onChange={this.handleChange}/>
                                        <label class="custom-control-label" for="customCheck">I agree to terms and conditions of leaty</label>
                                    </div>
                                    </div>
                                <div class="pull-right">
                                <Link to="/forget_password" >Forget Password ?</Link>
                                </div>
                            </div>
                            <div class="form-group text-center">
                                <button type="submit" class="btn">Sign in </button> 
                            </div>
                            <div class="form-group text-center">
                                <p>If you are already a member Please <Link to="/login" >Sign in</Link></p>
                            </div>
                        </form>
                    </div> 
                </div>
            </div>
        </div>
    </div>

          );
    }
}


 export default Signup;

Action

export  default class Register{
    static Create(payload){

        return {
            type: "REGISTER",
            payload:payload,
        };
    }
}
console.log('Success')

Reducer

import RegisterService from "../API/RegisterService";
import store from '../store/store';
const initialState  = {
    REGISTER:{},
    loading:false,
    success:{},
    error:{},
};

const REGISTER_REDUCER=(state= initialState,action)=>{
    const payload = action.payload;

    switch(action.type){
        case "REGISTER":
            RegisterService.UserRegister(payload)
            .then(response=>{
                store.dispatch({type:'REGISTER_SUCCESS',payload:response});

            })
            .then(error=>{
                store.dispatch({type:'REGISTER_ERROR',payload:error});
                });
            return {
                ...state,
                loading:true

            };
            break;
        case "REGISTER_SUCCESS":
               console.log(payload.result.id,"ID")
               localStorage.setItem('userId',JSON.stringify(payload.result.id))
            return{
                ...state,
                loading:false,
                REGISTER:payload.result,

            };     

            break;
        case "REGISTER_ERROR":
                return{
                    ...state,
                    loading:false,
                    error:payload,
                };  
                break;

            default:
                return state;
                break;
    }

}

export default REGISTER_REDUCER;

Upvotes: 0

Views: 90

Answers (1)

evolon
evolon

Reputation: 1586

You can use <Redirect to="/your/path" /> in your render method.

  1. Define a state like isSignedIn in your Redux State.
  2. Connect your component to listen to that state.
  3. Now, whenever the isSignedIn is being set to true, your component will redirect to your new path instead of rendering your signup form.
  4. Now you can set the isSignedIn from within your Redux, right after the login is successful.

So your component should look like something like this:

import {Redirect} from 'react-router-dom';

...

class SignUp extends Component {

   ...

   render() {
       if (this.props.isSignedIn) {
           return <Redirect to="/your/path" />
       }

       ...
   }
}

const mapStateToProps = state => ({
    isLoggedIn: state.isSignedIn
})

export default connect(mapStateToProps)(SignUp)

And P.S: avoid calling outside functions (having side effects) in your reducer function. You can use action creators to take care of those side effects. The reducer functions should be pure and only change the state based on the function arguments, nothing more.

Upvotes: 1

Related Questions