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?