Home > Enterprise >  share state between slices redux toolkit?
share state between slices redux toolkit?

Time:06-27

any idea how to pass state data from one slice to another slice , in other words slice b can have access to slice a... it tried to use getState() inside the other slice but it is causing a reference error , what is the right way to go about this ?

// Slice A 
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from './store';

type userType = { user: ''} 

export interface globalState {
  currentUser: userType;
}

const initialState: globalState = {
  currentUser: { user: '' },
};

export const globalSlice = createSlice({
  name: 'global',
  initialState,
  reducers: {
    setUser: (state, action: PayloadAction<{ user: string }>) => {
      state.currentUser = { user: action.payload.user }
    },
  },
});

export const GlobalCurrentState = (state: RootState) => state.global;
export const { setUser} = globalSlice.actions;

export default globalSlice.reducer;
// Slice B
import { RootState, store } from './store';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface infoState {
  info: { data: string };

}

const initialState: infoState = {
  info: { data : '' },
};

export const infoSlice = createSlice({
  name: 'info',
  initialState,
  reducers: {
    addName: (state, action: PayloadAction<{ select: string; value: string }>) => {
      const updateData = async () => {
      // this line is casuing a refrence erorr the slice cannot see the info form the other slice. 
      let fromStateA = store.getState().currentUser
    },
});

// Values
export const infoCurrentState = (state: RootState) => state.info;
// Action creators are generated for each case reducer function
export const { addName } = infoSlice.actions;
export default infoSlice.reducer;

CodePudding user response:

This is not intended and not possible - slices in Redux are independent of each other and know about nothing in the world except about their own state and the contents of the action being passed in. You can experiment with some custom kind of hand-written reducer, or a library like reducer-reducers, but most of the time you are either splitting logic that should be one slice into two, or you don't pass enough information into your action.

  • Related