'redux toolkit reducer with multiple parameters? redux toolkit
Given this
export const slice = createSlice({
name: 'reducer',
initialState: {
},
reducers: {
test: (state, action) => {
console.log(action.payload) // 1
}
},
})
then I run this
dispatch(test(1,2,3,4,5,6,7))
action.payload
is only the 1st parameter. How do I get the other 6?
Solution 1:[1]
Read the relevant documentation
By default, the generated action creators accept a single argument, which becomes
action.payload
. This requires the caller to construct the entire payload correctly and pass it in.
So you could do call the action with
dispatch(test([1,2,3,4,5,6,7]))
this way, the payload will now be the array you passed.
If, however, you need to be able to call it with multiple arguments, you can use the prepare
callback
If you want to add a
meta
orerror
property to your action, or customize thepayload
of your action, you have to use theprepare
notation.
export const slice = createSlice({
name: 'reducer',
initialState: {
},
reducers: {
test: {
reducer(state, action){
console.log(action.payload) // 1
},
prepare(...arguments){
return {
payload: arguments;
}
}
}
},
});
This way, your original way of calling the action will again result in a payload of an array which will contain all the arguments you passed, regardless of their number.
Solution 2:[2]
Yes, We can send multiple parameters in redux reducer but after wrapping inside single object. Single object parameter can be array or JSON object.
// as an array
dispatch(test(["first","second","third"]));
// as a JSON object
dispatch(test({ first:1, second:2, third:3 }));
your result will be like this.
export const slice = createSlice({
name: 'reducer',
initialState: {
},
reducers: {
test: (state, action) => {
console.log(action.payload) // ["first","second","third"]
// or in case of JSON object
console.log(action.payload) // { first:1, second:2, third:3 }
}
},
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gabriele Petrioli |
Solution 2 | Riya Patadiya |