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 do we use string here and why we use this in an array ( [incrementBy] )?
Please help, thank you a lots
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);
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]));