Error: Trying to access a property that is not defined (reference to 'user')

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

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: null,
  },
  // The `reducers` field allows us to define reducers and generate associated actions
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
  
  });
  
export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;



export default userSlice.reducer;

Error: userSlice.js:22 Uncaught TypeError: Cannot read properties of undefined (reading 'user') at selectUser (userSlice.js:22:1)

Answer №1

To retrieve the user, it is necessary to utilize configureStore along with useSelector.

Step 1:

You can create a new file called store or give it any desired name.

import { configureStore } from "@reduxjs/toolkit";
import User from "./slices/userSlice";

const store = configureStore({
 reducer: {
  User: User,
 },
});

export default store;

Step 2:

In the index.js file, you need to include the provider as shown below:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store/index";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
 <Provider store={store}>
  <App />
 </Provider>
);

Step 3:

Utilize useSelector to access the user from anywhere in this manner:

const user = useSelector((state) => state.User.user); 
console.log(user);

Answer №2

const getUser = (state) => state.user === null ? '' : state.user.user;
// or
const fetchUser = (state) => state.user === null ? {} : state.user.user;

Answer №3

To optimize your code, consider declaring the initial state outside of the createSlice function:

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

const defaultUserState = { user: null }

export const userSlice = createSlice({
  name: 'user',
  initialState: defaultUserState,
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
  
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;

export default userSlice.reducer;

Alternatively, you can simplify by directly providing an object as the initial state:

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

export const userSlice = createSlice({
  name: 'user',
  initialState: { user: null },
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
  
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;

export default userSlice.reducer;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Async Laziness Loading

At the moment, our team is utilizing the SAP HANA Database for data storage. We plan to retrieve this data using a Node.JS-API through AJAX calls in order to take advantage of asynchronous processing. However, we have encountered a challenge: Across multi ...

Trigger an Angular controller within Foundation's reveal modal

Trying to implement a form using foundation's reveal modal, I want to incorporate an angular controller within the form for ajax form submission instead of the default post/refresh behavior. This is my primary view: <html lang="es" ng-app="crm"&g ...

Common issue with setting up createContext and using useContext in Next Js

Hey there! I'm a beginner with Next.js and I've run into an error that I can't seem to figure out. I'm not sure what's causing it or how to troubleshoot it. Here are some screenshots and code snippets: https://i.sstatic.net/6MVWgRB ...

Ways to implement a time delay when adding a mesh to a scene in three.js

I'm trying to incorporate a mesh into the scene with a time delay, but I'm having trouble getting the setTimeout function to work properly. var geometry = new THREE.BoxGeometry(1, 1, 1); var material = new THREE.MeshLambertMaterial({color: 0xFF0 ...

Selenium with Python: A class focused on link text

Currently, I am encountering a challenge while using Python and Selenium to scrape content from a specific webpage. The issue lies in the presence of multiple div-classes with identical names but distinct content. My requirement is to extract information f ...

How can you utilize Angular Signals in combination with HostBinding to dynamically update styles?

Within a component called app-test, the following code is present: @Input({ transform: booleanAttribute }) reverse: boolean = false; @HostBinding('style.flex-direction') direction: string = this.reverse ? 'column-reverse' : &ap ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

Demonstrate how to pass a newline character from Ruby on Rails to JavaScript

I am working with a .js.erb file that is activated by a JavaScript function. Within this js.erb file, I have the following snippet of code: event = <%=raw @event.to_json %> $('#preview-event-body').html(event.body); The value of event.bo ...

Create a unique V-MODEL for each index that I generate

How can I customize the V-MODEL for each object generated? I am developing a cupcake website where users can create multiple forms with just one submission. However, when generating two fields, the inputs of the second field are linked to the inputs of t ...

Troubleshooting challenges arise with Bootstrap's button group spacing issue

I am encountering spacing issues with the markup provided below. <h2>Profitability Report</h2> <form method="post"> <div class="row"> <div class="col-md-12"> <div class="btn-group btn-group-toggle ...

What could be causing the issue with the theme not functioning properly in Material-UI?

I'm currently working on implementing a unique theme-switching feature in my web application, allowing users to toggle between light and dark modes. Utilizing the Material-UI framework combined with React, here's the code snippet: const theme = c ...

Is there a way for my discord bot to notify me when a certain user is playing a particular game?

How can I set up my bot to automatically send a message when a specific user starts playing a specific game, like Left 4 Dead 2? I'm looking for a way to do this without using any commands. // Game Art Sender // if (message.channel.id === '57367 ...

Checking for the Existence of a Database Table in HTML5 Local Storage

Upon each visit to my page, I automatically generate a few local database tables if they do not already exist. Subsequently, I retrieve records from the Actual Database and insert them into these newly created local tables. I am wondering if there is a me ...

Ensure that the header stays centered on the page as you scroll horizontally

Below is a given code snippet: header { text-align: center; } /* This section is just for simulation purposes */ p.text { width: 20rem; height: 50rem; } <html> <body> <header> <h1>Page Title</h1> <detail ...

Retrieving information from Prismic API using React Hooks

I'm having trouble querying data from the Prismic headless CMS API using React Hooks. Even though I know the data is being passed down correctly, the prismic API is returning null when I try to access it with React Hooks. Here is my current component ...

Vows.js: Utilizing data from parent topics in nested topics

Is there a way to access the return value of an outer topic from within a test in an inner topic? To clarify, consider this example: "build.css" : { topic : function(file) { fs.readFile(fixtures + "/public/build.css", "utf8", this.callback); }, ...

JavaScript - Shuffle Cards Memory Game Function

I've been working on developing a memory game using JavaScript, and I've encountered some challenges along the way. After successfully designing the HTML and CSS components, my focus has now shifted to implementing the JavaScript functionality. O ...

When I submit a form with an empty date input field, the Datepicker is sending a 0000-00-00 date

[I am experiencing an issue with my date input field. When I submit without entering any value, the date on the view page shows as 0000-00-00 instead of being empty or blank.] <div class="col-sm-3 col-sm-offset-1"> <div class="input-group"& ...

Error: Unable to iterate through the {(intermediate value)}. It's not a function

Snippet of the original code: const genreOptions = [{{ genreOptions | json_encode | raw }}].map((type , label) => ({value: type, label: label})); Piece of debugging code: const genreOptions = { "Horror": "Kork ...

Prevent popup content from refreshing: Tips for creating a dynamic user experience

Currently, I am working on a website that is similar to Facebook. One of the features I am implementing is the ability for users to like posts or photos and see who has liked them. However, I am facing an issue with the popup that shows the list of people ...