Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call other reducers in createSlice to change state?

I use redux to createSlice, here is my createSlice looks like:

export default createSlice({
    name:'testSlice',
    initialState,
    reducers:{
        setRecords: setRecordsReducer,
        setObjects: setObjectsReducer,
        setBoth:....
    }
});

Here is setRecordsReducer and setObjectsReducer look like:

const setRecordsReducer = (state, {payload:{id,recordName}}) => {
    return {...state, items:{...state.items, records:{...state.items.records, [id]:{recordName}};
};

const setObjectsReducer = (state, {payload:{id,objectName}}) => {
    return {...state, objects:{...state.objects, records:{...state.objects.records, [id]:{objectName}};
};

The two reducer setRecordReducer and setObjectsReducer change different parts of the state (actually not change the state, but build new state based on it). setRecordReducer returns new state based on state.items.records; setObjectReducer returns new state based on state.objects.records.

I tried to create a new action setBoth, can I call both setRecordReducer and setObjectsReducer when action setBoth happens? So the two parts of the state can be changed and return me the new state?

like image 937
spspli Avatar asked Dec 06 '25 18:12

spspli


1 Answers

Since the state each is operating over then yes, I see no reason why you couldn't write a reducer function that called the others and passed the appropriate arguments. This new reducer function needs to also return the next computed state value, returned the combined updated state from each reducer function called.

const setBothReducer = (state, action) => {
  return {
    ...state,
    ...setRecordsReducer(state, action),
    ...setObjectsReducer(state, action),
  };
}

export default createSlice({
  name:'testSlice',
  initialState,
  reducers:{
    setRecords: setRecordsReducer,
    setObjects: setObjectsReducer,
    setBoth: setBothReducer,
  }
});
like image 86
Drew Reese Avatar answered Dec 09 '25 00:12

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!