Home > Software design >  Dispatch with multiple parameters and create action with Redux Toolkit
Dispatch with multiple parameters and create action with Redux Toolkit

Time:04-30

I'm fairly new to Redux (and especially Redux Toolkit) and cannot wrap my head around the following issue.

I'm rewriting old code with Toolkit.

I understand that I can do the following in my createSlice.

  reducers: {
    changeDay: (state, action) => {
      state.day = action.payload;
    }
}

and dispatch like this:

  store.dispatch(changeDay(true));

Many scenarios in my application however take in second arguments, given the example from old redux without toolkit

case ACTIVITY:
  return {
    activity: action.data.first,
    anotheractivity: action.data.second,
  };

The action for this looks as following:

function clickedActivity(first = undefined, second = undefined) {
  const data = {
    first,
    second,
  };
  return {
    type: ACTIVITY,
    data,
  };
}

In this case, I was able to call dispatch(clickedActivity(first,second)) and would get both values as desired.

I assume that I have been looking for the wrong keywords in the documentation as I could not find a solution for this. Any hints?

CodePudding user response:

You can pass an object in action.payload. So for example,

// assume you wanted to pass multiple parameters in reducer function changeDay

store.dispatch(changeDay({ type:ACTIVITY, data,}));


// Now inside the reducer, you can receive it like this

 reducers: {
    changeDay: (state, action) => {
      const {type,data}=action.payload; // You will receive the properties like this

    }
}


  • Related