Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138221

How to set state before render with react(redux)

$
0
0

I want to make a component able to redirect when not loggedIn. Components were made with react, checking auth function works well with redux.

//App.js
class App extends Component {
  checkUserInfo () => {
    const loggedInfo = storage.get('loggedInfo');
    if(!loggedInfo) return;
    const { UserActions } = this.props;
    UserActions.setLoggedInfo(loggedInfo)
  }

  constructor(props) {
    super(props);
    this.checkUserInfo();
  }

  render() {
    console.log(this.props.logged)
    return(...)
  }
}

export default connect((state) => ({logged: state.user.get('logged')}, (dispatch)=> ...)

and UserActions.setLoggedInfo action is look like this.


...
export default handleActions({
  [SET_LOGGED_INFO]: (state, action) => {
    return state.set('logged', true)
  }
})
...

So, I want situation that component is redirected when auth is not logged in. I made a rendering component <Route/> with condition which is that if state.logged==false, <Redirect to='login/>.

But in very front point, logged is false before executing checkUserInfo function. so when I'm loggedIn, Redirect to /login, and when I'm not loggedIn, Redirect to /login too.

//PrivateRoute.js
...
  render() {
     const { logged } = this.props;
     console.log(logged);
     return(
      <Route path="/myPage" render={props =>
        logged ? <Component/> : <Redirect to={{pathname: '/login'}}/>
      }/>
    )
  }
...

this is screenshot what is logged value in console.

enter image description here

I want to skip very front state before set state by myFunction(checkUserInfo), how can I do.

plz help me. and sorry to not good english syntax.


Viewing all articles
Browse latest Browse all 138221

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>