jose azevedo
jose azevedo

Reputation: 245

Get a store value on a component with Redux

I have this store with this element:

loggedIn:false

What I want to do is to block the user to go to any pages if he hasnt logged in yet. When he logged in successfully the boolean changes to true on other component.

To block him from accessing other links of my application I created a component called Refresh Route that does this:

import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";

const RefreshRoute = ({ component: Component, ...rest }) => {
const canGo=this.props.loggedIn;
window.alert(canGo)
return (<Route
    {...rest}
    render={props =>
        canGo ? (
            <Component {...props} />
        ) : (
                <Redirect
                    to={{
                        pathname: "/login"
                    }}
                />
            )
    }
/>)
}

 const mapStateToProps = state => {
  return {
    loggedIn: state.atuth.loggedIn
 }
}

export default connect(mapStateToProps)(RefreshRoute); 

My problem is that the props is null and I don´t know why.

Here hes the component where I call my Refresh Route:

const Routes = () => (
 <main>
 <Switch>
  <Route exact path='/' component={Main} /> 
  <Route exact path='/customers' component={Customers} />
  <Route exact path='/customers/:market' component={CustomersByMarket} />
  <Route exact path='/customers/:market/:customer' component={Customer} />
  <Route exact path='/customers/:market/:customer/:environment' component={MessageDashboard} />
  <RefreshRoute exact path='/home' component={Main}/>
  <Route exact path='/addPermission' component={AddPermissions}/>
  <Route exact path='/excludePermission' component={RemovePermissions}/>
  <Route exact path='/login' component={SignIn}/>
</Switch>

)

export default Routes;

Upvotes: 0

Views: 466

Answers (2)

Andrea
Andrea

Reputation: 3440

The problem is here:

const RefreshRoute = ({ component: Component, ...rest }) => {
    const canGo=this.props.loggedIn;

You are destructuring the input props using { component: Component, ...rest }. So the property loggedIn will be inside rest.loggedIn:

const RefreshRoute = ({ component: Component, ...rest }) => {
    const canGo = rest.loggedIn;

Otherwise, you can explicit the loggedIn inside the destructured argument and use it:

const RefreshRoute = ({ component: Component, loggedIn, ...rest }) => {
    const canGo = loggedIn;

Upvotes: 1

bsekula
bsekula

Reputation: 919

In function components you do not have this.props therefore change:

const RefreshRoute = ({ component: Component, ...rest }) => { 
  const canGo=this.props.loggedIn; // props is not bound to this
  ...
}

to:

const RefreshRoute = (props) => { 
  const canGo = props.loggedIn
}

Or in your case:

const RefreshRoute = ({ component: Component, ...rest }) => {
  const canGo = rest.loggedIn
}

Upvotes: 1

Related Questions