0

I am trying to make protected routes with react and redux , i have made actions on redux for initaiting auth()! Here's a route :

    <BrowserRouter baseName="/">
                        <Switch>
                            <PublicRoute  authenticated={this.props.isAuthenticated} exact path="/loginapp" component={LoginApp}  />
                            <PrivateRoute  authenticated={this.props.isAuthenticated} exact path="/dashboard" component={dashboardContainer} />
                            <PrivateRoute  authenticated={this.props.isAuthenticated} exact path="/leaderboard" component={leaderBoardContainer} />
                        </Switch>
                    </BrowserRouter>

Here's the custom route:


export const PublicRoute = ({component: Component, authenticated, ...props}) => {
    const { from } = props.location.state || { from: { pathname: "/dashboard" } };
    return (
        <Route
            {...props}
            render={(props) => authenticated === true
                ? <Redirect to={from} />
                : <Component {...props} />}
        />
    );
};


class PrivateRoute extends React.Component  {
    render() {
        const { component: Component, authenticated, ...rest }  = this.props;
        const isLoggedIn = authenticated;

        return (
            <Route
                {...rest}
                render={props => isLoggedIn 
                    ? <Component {...props} />
                    : <Redirect to={{ pathname: "/loginapp", state: {from: props.location }}} />}
            />
        );
    }
};

I have got 3 routes , /loginapp, /dashboard, /leaderboard , in which , i wanted the user shouldn't view /loginapp route again if the user refreshes the page and automatically should be logged in with the data saved in redux . But when i refresh the page the data gets lost and IT STAYS IN /LOGINAPP route AND I HAVE TO MANUALLY LOGIN.

Here is my loginapp code:

import PropTypes from "prop-types";
import * as actions from "../store/actions";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import classes from "./LoginApp.scss";

class LoginApp extends Component {

    constructor(props) {
        super(props);
    }

    pushme =() => {
        console.log("==================");
        this.props.initAuth();
        this.props.authHandler();
    }


    loginFormHandler = () => (
        <div>
            <span>this is login page</span>
            <button type="button" onClick={this.pushme}>get login</button>
        </div>
    );

    render() {
        return (
            <div className={classes.LoginApp}>
                {this.loginFormHandler()}
            </div>
        );

    }
}

LoginApp.propTypes = {
    initAuth: PropTypes.func,
    authHandler: PropTypes.func,
    isAuthenticated: PropTypes.bool,
    location: PropTypes.object
};


const mapStateToProps = state => {
    return {
        isAuthenticated:  state.auth.isAuthenticated
    };
};

const mapDispatchToProps = dispatch => {
    return {
        initAuth: () => dispatch(actions.initAuth()),
        authHandler: () => dispatch(actions.authSignIn())
    };
};
export default connect(mapStateToProps,mapDispatchToProps)(LoginApp);

here is the action creator / and the reducer is already created by me:

export const authSignIn = () => async (dispatch) => {
    const success = await auth.signInWithEmailAndPassword("iphonexs@apple.com", "12345678").catch((error) =>  console.error(error));
    success.user.uid !== undefined ?
        dispatch(authSuccess(success.user.displayName)) : 
        dispatch(authFailed("INVALID : FAILED TO LOG IN "));

};

Please have a look. i have been stuck .

0xAnon
  • 847
  • 9
  • 20

1 Answers1

1

i wanted the user shouldn't view /loginapp route again if the user refreshes the page and automatically should be logged in with the data saved in redux . But when i refresh the page the data gets lost and IT STAYS IN /LOGINAPP route AND I HAVE TO MANUALLY LOGIN.

That's the expected behavior. Redux is not a persistent data store, when you reload the page everything will be gone. To persist authentication status across reloads, you would need to save the state in sessionStorage or localStorage with regard to your needs.

Also the following question may be helpful for you.

frogatto
  • 28,539
  • 11
  • 83
  • 129