behappy8
behappy8

Reputation: 61

After send value with mapDispatchToProps, redux Initial state is undefine

Hello I am making login app used firebase google login. I want to save the user in the user-reducer. The console shows user info from the firebase! but, It keeps shows undefined. I don't know why it shows like these. Please advised!

enter image description here

[user-action ]
import { UserType } from './user.types';
export const login = ({ currentUser }) => ({
  type: UserType.USER_LOGIN,
  payload: currentUser,
});

[user-types ]

export const UserType = {
  USER_LOGIN: 'USER_LOGIN',
};

[user-reducer]

import { UserType } from './user.types';
const INITAIL_STATE = {
  user: [],
};
const userReducer = (state = INITAIL_STATE, action) => {
  switch (action.type) {
    case UserType.USER_LOGIN:
      return {
        ...state,
        user: action.payload,
      };
    default:
      return state;
  }
};

export default userReducer;


[Login.js]


const Login = ({ googleLogin }) => {
const [currentUser, setCurrentUser] = useState(null);

  const getUser = new Promise((resolve, reject) => {
    console.log('doing...');
    firebase.auth().onAuthStateChanged(setCurrentUser);
    resolve(currentUser);
    console.log(currentUser);
  });

  getUser
    .then(user => {
      googleLogin(user);
    })
    .catch(error => {
      console.log(error);
    });

 .... 

const mapDispatchToProps = dispatch => ({
  onModal: () => dispatch(modalHandler()),
  googleLogin: currentUser => dispatch(login(currentUser)),
});

export default connect(null, mapDispatchToProps)(Login);

Upvotes: 1

Views: 37

Answers (2)

andy mccullough
andy mccullough

Reputation: 9551

export const login = ({ currentUser }) => ({
  type: UserType.USER_LOGIN,
  payload: currentUser,
});

should be -

export const login = (currentUser) => ({
  type: UserType.USER_LOGIN,
  payload: currentUser,
});

i.e no destructuring of currentUser

OR

googleLogin: currentUser => dispatch(login(currentUser))

should be

googleLogin: currentUser => dispatch(login({currentUser}))

Upvotes: 2

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

Your problem is on getUser, you are resolving promise passing a state variable (currentUser) that may have been not setted (because setCurrentUser is async). I would suggest to modify you code in this way:

  const getUser = new Promise((resolve, reject) => {
    console.log('doing...');
    firebase.auth().onAuthStateChanged(firebaseUser => {
      setCurrentUser(firebaseUser);
      resolve(firebaseUser);
      console.log(firebaseUser);
    });
  });

Upvotes: 2

Related Questions