1
votes

I can't use default state value in redux

Hello, I have a function to dispatch Login action, I want in the initial to be false,

but when I put this value in the render method, it's given me an error

can't read property 'isLogin' of undefined

although in the reducer i add an initialState

let initialState = {
  isLogin: false,
};

const userReducer = (state = initialState, action) => {
  switch (action.type) {
    case IS_LOGIN:
      state = {
        ...state,
        isLogin: true,
      };
      break;
    default:
      return state;
  }
  return state;
};

here's Store

const store = createStore(
  combineReducers({
    user: userReducer,
    count: countPlayReducer,
  }),
);

Action

export const isLoginFunc = isLogin => {
  return {
    type: IS_LOGIN,
    payload: isLogin,
  };
};

UI/Dispatching

import {isLoginFunc} from '../../redux/actions/isLoginAction';

 signIn = async data => {
   this.setState({loading: true}); // maybe here the wrong?
   API.post('/login', data)
    .then(async response => {
     let {
       data: {
         data: {
           response: {token},
         },
      },
    } = response;
    this.props.dispatch(isLoginFunc(true));
    await saveToken('id_token', token);
    this.setState({loading: false}, () =>
      this.props.navigation.navigate({
        key: 'TabHome',
        routeName: 'TabHome',
      }),
    );
  })
  .catch(error => {
    console.log(error);
    this.setState({loading: false, error: error.response.data});
  });

};

render(){
    ...
      <Text>{this.props.user.isLogin}</Text>
    ...
}

mapStateToProps = state => {
  return {
    isLogin: state.user,
  };
};

export default connect(mapStateToProps)(Login);
1

1 Answers

4
votes

It looks like you're mapping redux state using the following:

mapStateToProps = state => {
  return {
    isLogin: state.user,
  };
};

But then you're trying to access isLogin via:

this.props.user.isLogin

Looks like this should be changed to:

this.props.isLogin.isLogin

However you might want to alter your mapping to the following instead:

mapStateToProps = state => {
  return {
    isLogin: state.user.isLogin,
  };
};

So that you can simply use:

this.props.isLogin