Home > Software design >  What is extraReducers map object notion
What is extraReducers map object notion

Time:10-31

When read redux toolkit offical documet, i saw this in createSlice section:

const incrementBy = createAction('incrementBy')

createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {},
  extraReducers: {
    [incrementBy]: (state, action) => {. ///what is this
      return state   action.payload
    },
    'some/other/action': (state, action) => {},
  },
})

I don't understand why we have array here. , why we use string here and why we use this in an array ( [incrementBy] )?

Please help, thank you a lots

CodePudding user response:

This is not an array, instead this is computed properties. This will add key to an object at run-time

let prop = "name";
const obj = {
  [prop]: "Stackoverflow",
};
console.log(obj);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

extraReduce is an object and in the code incrementBy will give property name, also you are assigning a function to that property name.

let prop = "getSum";
const obj = {
  [prop]: (arr) => {
    return arr.reduce((acc, curr) => acc   curr, 0);
  },
};
console.log(obj[prop]([1, 2, 3, 4, 5]));
console.log(obj.getSum([1, 2, 3, 4, 5]));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related