Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 881
Bas Avatar asked Mar 09 '26 22:03

Bas


2 Answers

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 or error property to your action, or customize the payload of your action, you have to use the prepare 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.

like image 161
Gabriele Petrioli Avatar answered Mar 12 '26 10:03

Gabriele Petrioli


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 }
   } 

},

})
like image 39
Riya Patadiya Avatar answered Mar 12 '26 12:03

Riya Patadiya



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!