CleverProgrammers / cp-disney-plus-clone

Here's the DEMO Disney+ Clone App
https://disney-clone-d1e27.web.app
337 stars 261 forks source link

reduxjs/toolkit: Uncaught TypeError: Cannot read properties of undefined (reading 'name') #16

Closed githubarj closed 1 month ago

githubarj commented 2 years ago

[FIX] Uncaught TypeError: Cannot read properties of undefined (reading 'name')

I got this error when working on the login functionality Uncaught TypeError: Cannot read properties of undefined (reading 'name').

It was a particularly frustrating error as there is not a lot of documentation on it however there is a lot of unsolved questions about it on stack overflow and GitHub actions.. Going through the YouTube comments I realise a lit of people had the same issue. so I decided to put the solution here.

So this has to do with the userSlice.js file.

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  name: "",
  email: "",
  photo: "",
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    setUserLoginDetails: (state, action) => {
      state.name = action.payload.name;
      state.email = action.payload.email;
      state.photo = action.payload.photo;
    },

    setSignOutState: (state) => {
      state.name = null;
      state.email = null;
      state.photo = null;
    },
  },
});

export const { setUserLoginDetails, setSignOutState } = userSlice.actions;

export const selectUserName = (state) => state.user.name;
export const selectUserEmail = (state) => state.user.email;
export const selectUserPhoto = (state) => state.user.photo;

export default userSlice.reducer;

The issue is with the exports, the exports are

export const selectUserName = (state) => state.user.name;
export const selectUserEmail = (state) => state.user.email;
export const selectUserPhoto = (state) => state.user.photo;

deleting the user part so that they match their declarations to the reducer as shown below now solves the error

export const selectUserName = (state) => state.name;
export const selectUserEmail = (state) => state.email;
export const selectUserPhoto = (state) => state.photo;