Zaben
Zaben

Reputation: 117

when i try to access redux state it returns undefined

I can dispatch my state but i have problem with with accesing it in redux

import React, {useEffect} from 'react';
import AuthenticationPage from './AuthenticationPage';
import '../styles/App.css';
import SignOut from './SignOut';
import{TOGGLE_LOGIN} from "../redux/actionTypes"
import{connect} from 'react-redux'

function App(props) {

  useEffect(()=>{
    if(window.localStorage.getItem('IsUserLogged')==="true"){
      props.toggleLogin();
    }
    console.log(props.isLogged);    //console show undefined  
  },[])

  return (
    <div className="App">
      {props.isLogged===true?
      <SignOut/>:
      <AuthenticationPage/>}
    </div>
  );
}

const mapStateToProps = state =>{
  return{
    isLogged: state.isLogged
  }
}

const mapDispatchToProps = dispatch=>{
  return{
    toggleLogin: ()=>dispatch({type: TOGGLE_LOGIN})
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

I have redux dev tools installed and It shows me that my state is working enter image description here

i can also toggle my state with props.toggleLogin(),enter image description here

but when i try to get value of my state with props.isLogged it returns undefined instead of true/false.

here is my redux code:

reducers/logIn.js

import{TOGGLE_LOGIN} from "../actionTypes"

const initialState={
    isLogged: false,
}

const LogInReducer = (state=initialState, action)=>{
    switch(action.type){
        case TOGGLE_LOGIN:{
            return Object.assign({}, state, {
                isLogged: !state.isLogged
            })
        }
        default:{
            return state;
        }
    }
}

export default LogInReducer;

reducers/index.js

import{combineReducers} from "redux";
import LogInReducer from './logIn.js';

export default combineReducers({
    LogInReducer
})

actions.js

import{TOGGLE_LOGIN} from "./actionTypes"

export const ToggleLogin=()=>({
        type: TOGGLE_LOGIN
});

actionTypes.js

export const TOGGLE_LOGIN="TOGGLE_LOGIN";
});

store.js

import {createStore} from 'redux';
import rootReducer from './reducers';

export default createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

Upvotes: 0

Views: 345

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

That's because in your combineReducer you have a LogInReducer key.

So the state is actually LogInReducer.isLogged (which is also seen in your redux-dev-tool screenshot).

You may want to do this:

const mapStateToProps = state => {
  const { isLogged } = state.LogInReducer;

  return {
    isLogged
  };
}

Upvotes: 2

Related Questions