Baspa
Baspa

Reputation: 1168

Can't get updated state from Reducer

I made a login function which updates the state in my reducer from false to true. I check this in my reducer and my login function. But when I want to check the state in another file it keeps returning false.

My login function:

axios
    .post('api/user/login', {
        username: this.state.username,
        password: this.state.password
    })
    .then(response => {
        return response;
    })
    .then(json => {
        if (json.data.success) {
            store.dispatch(loginStatus(true));
            console.log('Login: ' + store.getState().loggedIn);
            window.location.assign('/');
        } else {
            alert('Login Failed!');
        }
    })
    .catch(error => {
        alert('An Error Occured!' + error);
        console.log(error);
    });

Which returns true

My reducer:

import { LOGIN_STATUS } from "../constants/action-types";

const initialState = {
    loggedIn: false
};

const rootReducer = (state = initialState, action) => {
    switch (action.type)  {
        case LOGIN_STATUS:
            state.loggedIn=action.payload;
            console.log('Reducer: ' + state.loggedIn);
            return {
                loggedIn: state.loggedIn=action.payload
            };
        default:
            return state;
    }
};

export default rootReducer;

Which also returns true

But then in my other file:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import  store from '../store/index';

const privateRouter = ({component: Component, ...rest }) => {

    const isLoggedIn = store.getState().loggedIn;
    console.log('PrivateRoute: ' + isLoggedIn);

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

export default privateRouter;

it returns false. Am I doing something wrong with getting the state? Because in my login function it does return the updated state.

Update:

This is my router by the way:

   <Provider store={store}>
        <Router>
            <Switch>
                <Route path={'/login'} component={Login}/>
                <Route path={'/register'} component={Register}/>
                <PrivateRoute path={'/'} component={Home}/>
            </Switch>
        </Router>
    </Provider>

Upvotes: 0

Views: 60

Answers (1)

glnrk
glnrk

Reputation: 58

It seems your "privateRouter" function not triggering once the reducer changes the state. You need to trigger privateRouter function in order to get the latest store. Instead of importing store use "Provider" and "connect" to pass state to components.

https://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/

Upvotes: 2

Related Questions