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

Are there any drawbacks to converting all instance methods into arrow functions in order to prevent binding loss?

What are the potential drawbacks of converting all instance methods into arrow functions to avoid the "lost binding" issue? For example, when using ReactJS, the statement onClick={this.foo} can lead to lost binding, as it translates to createElement({ ... ...

Place the object into a vacant area with the help of jQuery Sortable

I am using jQuery Sortable and it's functioning well. However, I have encountered a small issue that I need help with.    I have two blocks where elements from one block can be moved to the other. The problem arises when all the elem ...

Monochrome Effect Triggered by Cursor Hover

I'm attempting to use Javascript with HTML5 canvas to convert an image to greyscale, but I seem to be missing something in my code. Can anyone spot the error? I feel like I'm very close! function grayscaleConversion(str) { // Access the Canv ...

Tips for adding an asterisk to the label of a Material-UI switch component

I am trying to include an asterisk symbol in the label by passing a required prop with a property, but it doesn't seem to be functioning correctly. <FormControlLabel control={ <Switch onChange={event => ...

What is the best way to incorporate async/await in a useEffect hook in a React Native application?

Upon executing useEffect, my objective is to retrieve the token from AsyncStorage, fetch the data value using the axios.post('/auth/me') endpoint, and trigger the KAKAOLOG_IN_REQUEST action through dispatch. After verifying that the data value i ...

Issue with HTML5 Canvas y-axis dimensions

I am attempting to create a basic animated HTML canvas with a moving block controlled by WASD keys. I encountered an issue where drawing a 5x5 rectangle appeared to be 5x10 on the canvas. Upon inspecting my code and logging the position of the element, I d ...

Execute PHP code upon JavaScript confirmation

Whenever I update the status, an email is automatically sent. The issue is that it sends the email again if any other field is updated as well. What I want is a confirmation prompt before sending the email. I tried using AJAX to handle this, but even thoug ...

Updating React props using useState?

Below is a component that aims to enable users to update the opening times of a store. The original opening times are passed as a prop, and state is created using these props for initial state. The goal is to use the new state for submitting changes, while ...

Real-time functionality in React component and Apollo Client is not functioning as expected

I am struggling to develop a user system as it is not working in real-time, causing confusion for me. To illustrate my problem and code, I have set up a sample Sandbox. Please note that this example does not include any validation features and is solely f ...

Limit how API call costs are set in a function by throttling based on an argument

I am currently implementing express-throttle to restrict the number of API calls per IP address each day. I would like to dynamically set the 'cost' parameter in the 'options' array based on a value from the API request (refer to commen ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Continuously running React useEffect even with an empty dependency array

In my React application, I have implemented a hook system. Each sub-hook that is generated within this main hook is assigned a unique ID automatically. This ID is incremented by 1 every time a new sub-hook is created, ensuring uniqueness. const App = ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Error message: Unable to split path as a function when utilizing React hook forms in conjunction with Material UI

Check out this code snippet: <TextField name="name" required className='my-2 mx-auto' label="Full Name" variant="standard" style={{ "width": "60%" }} value={name} onChange={(event) => { set ...

Removing border of the top and bottom of jspdf pages

In my project, I am utilizing a combination of html2canvas, canvg, and jspdf to convert HTML content (which includes SVG graphs) into canvases for the purpose of creating a PDF file. To address some page-break issues, I have resorted to creating multiple c ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Neither setState() nor forceUpdate() trigger the rendering process

I am working with a basic React setup that resembles the following structure: index.js ReactDOM.render(<App />, document.getElementById('root')); App.js export default class App extends Component { constructor(props) { super ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Error caused by jQuery AJAX call: Receiving a 304 response code causes a problem

I am facing an issue with a script on my localhost that sends a GET request to the same domain. The response I am getting is a 304, which seems to be causing JQuery to treat it as an error. $(document).ready(function(){ $.ajax({ type: 'GE ...