Source:  Twitter logo

I've a login page with HOC I pass component which must render be after successful login.

Here, if I check for isLoggedIn and redirect in render of sigin-in for then I get error

err: Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops

saga.js

           try{//call api
                //put login success
              <Redirect to="/app"/>        
            }

index.js

          const AuthProfile=requireAuth(App);

           In reactdom
             <Route render={(props)=><AuthProfile  {...props}/>} path="/app"/>  


          import React, { PropTypes } from 'react';  
          import { connect } from 'react-redux';  
          import { push } from 'react-router-redux';
          import { bindActionCreators } from 'redux';

          export default function (ComposedComponent) {  
            class Authenticate extends React.Component {


              componentDidMount() {
                console.log("12ra")
                this._checkAndRedirect();
              }

              componentDidUpdate() {
                this._checkAndRedirect();
              }

              _checkAndRedirect() {
                const { isLoggedIn, redirect } = this.props;

                if (!isLoggedIn) {
                  redirect();
                }
              }

              render() {
                console.log("28ra")
                return (
                  <div>
                    { this.props.isLoggedIn ? <ComposedComponent {...this.props} /> : null }
                  </div>
                );
              }
            }

            const mapStateToProps = (state) => {
              return {
                isLoggedIn:state.signInReducer.isLoggedIn
              };
            };

            const mapDispatchToProps = dispatch => bindActionCreators({
              redirect: () => push('/')
            }, dispatch)

            //Authenticate.propTypes = propTypes

            return connect(
              mapStateToProps, 
              mapDispatchToProps
            )(Authenticate);
          }       

Is HOC component correct or I'm missing on something?

Is it good practise to redirect in saga?

Can anyone please lemme know how do I get to app component after success i'm stuck there please help thanks

UPDATE

saga.js

       yield put({type:LOGIN_SUCCESS,payload:data})
        yield put(push('/app'))

index.js

Ex for Page1,Page2 I need

        <AuthRoute
      exact
      path="/"
      component={Page1}
      redirectTo="/login"
      authenticated={this.props.isLoggegIn}
    />

     <AuthRoute
      exact
      path="/"
      component={Page2}
      redirectTo="/login"
      authenticated={this.props.isLoggegIn}
    />

Following is the way where you can navigate from saga:

saga.js

import { push } from 'react-router-redux';
...
// after API call & validate user
yield put(push('/app'));

index.js

 <Route strict exact path='/app' component={App}>
 <AuthRoute
          exact
          path="/"
          component={Yourcomponent}
          redirectTo="/login"
          authenticated={hasAccessToken()}
        />
7 users liked answer #0dislike answer #07
iamrajshah profile pic
iamrajshah

I am going to tell you the best and the simplest way from which you can redirect in any part of the application(i.e. inside redux and outside as well).

Step: 1 Create history.js file.

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Step : 2 Import it inside App.js file (or, where you have made routers of your application).

import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import history from './history';

const App = () => {
    return (<Router history={history}>
        <div className='App'>
            <Switch>
                <Route exact path={ROUTES.NOTIFICATIONS} component={Notification} />
                <Route exacr path={ROUTES.USER_PROFILE} component={UserProfile} />
                <Route exact path={ROUTES.SIGN_IN} component={SignInPage} />
                <Route exact path={ROUTES.SIGN_UP} component={SignUpPage} />
                <Route path='*' component={SignInPage} />
            </Switch>
        </div>
    </Router>
    );
};

export default App;

Step: 3 Inside Saga file just import the history.

import { push } from 'react-router-redux';
import { Auth } from "../service/api/Auth";
import history from '../containers/App/history';
import * as ACTION from '../constants/ActionType';
import { put, takeLatest, call } from "redux-saga/effects";
import { userLoginSuccess, userLoginFailed } from "../actions/auth";

export function* userLogin(loginData) {

  const payLoad = loginData.payload;
  try {
    const loginUserData = yield call(Auth.userLoginApiCall, payLoad);
    yield put(userLoginSuccess(TOKEN));
    history.push('/posts'); //  Redirect to Post Page
  } catch (err) {
    yield put(push(userLoginFailed()))
  }
}

export default function* userLoginRequest() {

  yield takeLatest(ACTION.USER_LOGIN_REQUEST, userLogin);
}
7 users liked answer #1dislike answer #17
Inamur Rahman profile pic
Inamur Rahman

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).