Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encountering difficulties in achieving this.

Below is the code snippet for userSlice.js:

import { createSlice } from '@reduxjs/toolkit'

const userNameLocalStorage =
    localStorage.getItem("userRedux") === null
        ? null
        : JSON.parse(localStorage.getItem("userRedux"));

const initialState = {
    userName: userNameLocalStorage,
}

export const userSlice = createSlice({
    name: 'users',
    initialState,
    reducers: {
        updateUser: (state, action) => {
            localStorage.setItem("userRedux", action.payload)
            state.userName = action.payload;
        },
        logOut: (state) => {
            window.localStorage.removeItem('userRedux');
            state.userName = null;
        },

    },
})

export const { updateUser,logOut } = userSlice.actions

export default userSlice.reducer;

The following is the code for cartSlice.js:

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

const initialState = {
    numberOfItems: 0,
    details: [],
    total: 0,
    user: userSlice?.initialState?.userName,
}
const cartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: {
    },

})

export default cartSlice.reducer;

Both of these files reside in the same directory.

Despite trying to import the userSlice and directly access userSlice.initialState.userName to set the initial value for the user property in cartSlice, I am not getting the expected result. The user property in cartSlice remains undefined.

How can I correctly retrieve the userName value from userSlice and assign it as the initial value for the user property in cartSlice? Is there something that I am overlooking or missing here?

Answer №1

To understand the Return Value of the createSlice() method, take a look at the following object structure:

{
    name : string,
    reducer : ReducerFunction,
    actions : Record<string, ActionCreator>,
    caseReducers: Record<string, CaseReducer>.
    getInitialState: () => State
}

You can utilize

userSlice.getInitialState().userName
to access the userName property.

Current package versions used:

"@reduxjs/toolkit": "^1.9.5",

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

Add jQuery and underscore libraries to an AngularJS component

For my new service, I am incorporating angularjs, underscore, and jQuery: myModule.factory('MyService', ['MyResource', function (MyResource) { .... // Utilizing _ and $ }]); How can I properly inject underscore and jQuery int ...

Incorporating map() with data passed down as props from App.js into child components

I have React version 18.2 and I want the child component in App.js to receive data and utilize the map() function. Although the child component successfully receives the data, it is encountering an issue when trying to use map(). An error message is disp ...

The issue encountered with the Material UI Autocomplete component is that it is not displaying the values

I'm currently attempting to extract a value from the state to be used in materialUI's autocomplete component. However, I've encountered an issue: The autocomplete feature works perfectly when selecting a value and saves it to the state wit ...

Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object: var obj = { arr1: [0, 1, 2], arr2: [1, 2, 3], arr3: [2, 3, 4] }; After pop()ing values from the arrays within the object, I ...

The NodeJS and Python-Shell .run function fails to display the standard output

I am currently working with NodeJS and a Python script. To retrieve results from my Python script, I have been using Python-Shell which you can find detailed documentation for at: github.com/extrabacon/python-shell Typically, to get prints from the scrip ...

Preventing the use of double-click on Grooveshark

I am currently in the process of creating a webpage to serve as a jukebox for parties. My goal is to have the page load Grooveshark with a transparent overlay (or any other necessary method) that can prevent users from forcefully adding their song to the f ...

I am experiencing issues with local storage getItem() function not functioning properly within NUXT JS

Currently working on creating a shopping cart using nuxt js. Successfully able to store the cart data in local storage, but facing difficulty in retrieving the data. Refer to the screenshots for more details: https://i.sstatic.net/X7dL9.png https://i.sstat ...

Adjust the placement of the fixed header waypoint or change its offset

Currently working on developing a Wordpress site with the Avada theme, my goal is to have a sticky header that starts immediately at the top of the page. This is the website in progress: The site I'm trying to emulate is synergymaids.com. If you vi ...

Prevent typing on input fields for numbers exceeding 3 digits

How can I prevent users from entering a number with more than 3 digits? For example, allowing entries like 150 but not accepting numbers like 1601. The keypress should be disabled in such cases. The keypress event must be disabled. <template> < ...

Converting the structure of an object into an array structure for highcharts can be achieved through

I am looking to transform the object structure below: [ { "tahun": "2010", "apel": 100, "pisang": 200, "anggur": 300, "nanas": 400, "melon": 500 }, { ...

What is the method for automatically starting another .mp4 video once the first one finishes playing?

I am currently trying to replicate the functionality of a television for a project. The idea is to play a .mp4 file, and once it ends, automatically select and play another .mp4 file. It's like mimicking the TV experience where one episode finishes a ...

upright scrolling mouse slider

In my project, I have implemented a vertical slider with mousewheel control using SwiperJS from https://swiperjs.com/. Although the slider is working perfectly fine, I am looking to fix the positions while scrolling on the page similar to the example pro ...

Are HTML's Regular Expressions the Equivalent of JavaScript's Regular Expressions?

I have been trying to utilize the pattern="" attribute in HTML to implement regex, but unfortunately, I am unable to locate a comprehensive list of HTML regex parameters. This has led me to ponder whether the syntax for regex in HTML is similar to JavaSc ...

What is the best way to create an HTML template with a table where the first column is divided into four cells and the second column only has one

Currently, I am working on a template using HTML and CSS. One issue that I am facing involves designing a table template with HTML and CSS. The specific problem occurs in the second row of the table where there are 4 cells in the first column and only one ...

Ensuring that all routes in Express 4 redirect from HTTP to HTTPS

Is there a way to redirect all http:// requests to https:// for every route in my express 4 application? I've tried this method, but it seems to cause a redirect loop error I'm currently utilizing the Express 4 Router in the following manner: ...

The glitch in jQuery's animate function callback

In my code to animate the sliding out of a div, I encountered an issue: var current = $('.s_text:visible'); current.animate({ right: 1014, opacity:0, },{queue: false, duration:2000}, function() { current.hide(); }); Strangely, the callbac ...

Tips for excluding files in a webpack configuration for a Vue application during the production build

I am attempting to remove an Html file named "dev.html" from the final product build. What configurations do I need to make in webpack for this? I understand that rules need to be applied, but where exactly do I need to configure them? Below is a snippe ...

When I implement the persist gate in Next.js with Redux, the flex direction automatically adjusts

I'm currently developing an app using next js and redux. An interesting issue has arisen - when I include PersistGate in my _app.js file, the flex direction mysteriously changes from row to column in index.js. There haven't been any modifications ...

Incorporate duration into date using angular

In my Firebase database, I store the following information: Timestamp for the day a record was created in Firebase. Terms entered by the user at the time of creation. For instance, it may look like this: 1439612582756 // converts to: Aug 14, 2015 15 / ...

Modifying the appearance of radio buttons using jQuery

I'm new to jQuery and I'm finding it challenging. Currently, I have a set of three radio buttons with the third button already prechecked. My aim is to change the CSS class of the checked button, making it similar to an unchecked button with the ...