Search code examples
javascriptreactjsreduxreact-reduxredux-toolkit

How can I pass multiple parameters to a redux reducer with Typescript?


I'm trying to pass multiple parameters to a RTK reducer using useDispatch. Typically I would wrap the parameters in an object or array and destructure in the reducer. But I'm having a tough time doing this with Typescript, other than using my famous cheat code "any". I feel this is an extremely ignorant question and showcases my newness to Typescript, but would appreciate any help!

types:

  • marker.id = string
  • e.nativeEvent.coordinate = {latitude: number, longitude: number}

dispatch in my map component:

dispatch(updateMarkerCoords([marker.id, e.nativeEvent.coordinate]))

rtk slice:

    updateMarkerCoords: (state, action: PayloadAction<Array<any>>) => {
      const [id, coords] = action.payload
      const marker = state.addNewField.markers.find((m) => m.id === id)
      if (marker) {
        marker.coords = coords
      }
    },

Solution

  • With Redux Toolkit, generated action creators only accept one argument by default. If you want to pass in multiple values, you need to do so as an object. And, the generic you provide to PayloadAction should define the fields and types in that object, such as:

    updateMarkerCoords(state, action: PayloadAction<{id: string, coordinate: number}>) {
      // use action.payload.id and action.payload.coordinate here
    }
    

    If you really want to pass them in as separate parameters, you can write a "prepare callback" that converts them into the single payload field yourself:

    updateMarkerCoordinate: {
      reducer(state, action: PayloadAction<{id: string, coordinate: number}>) {
        // same logic here
      },
      prepare(id: string, coordinate: number) {
        return {payload: {id, coordinate}}
      }
    }
    

    but most of the time it isn't worth it.