zaplec
zaplec

Reputation: 1819

How to create a redux store actionSanitizer when using PayloadActions?

I am trying to create an actionSanitizer to be used with devTools when configuring a store for redux. The problem is that stores are slices created with createSlice and there the reducers are defined as

createSlice({
  name: 'Something',
  initialState,
  reducers: {
   someReducer(
     state,
     action: PayloadAction<SomeType>
   ) {
    /** Do something **/
   }
  }
})

Now the action is of type PayloadAction.

// From redux toolkits createAction.d.ts
export declare type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
    payload: P;
    type: T;
} & ([M] extends [never] ? {} : {
    meta: M;
}) & ([E] extends [never] ? {} : {
    error: E;
});

actionSanitizer only accepts functions with type

  actionSanitizer?: <A extends Action>(action: A, id: number) => A;

This works, but obviously is not what I want

const devToolsConfiguration: DevToolsEnhancerOptions = {
  name: 'Qwerty',
  actionSanitizer: action => action,
};

const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk, logger],
  devTools: process.env.NODE_ENV === 'production' ? false : devToolsConfiguration
});

But then this solution, which tries to follow few other examples (1, 2) doesn't, because the types are not compatible

const devToolsConfiguration: DevToolsEnhancerOptions = {
  name: 'Qwerty',
  actionSanitizer: (action: PayloadAction<any>) => {
    action.type === "someAction" && action.data
    ? return { ...action, payload: '<<LONG_BLOB>>' }
    : action
  },
};

const store = configureStore({
  reducer: rootReducer,
  middleware: [thunk, logger],
  devTools: process.env.NODE_ENV === 'production' ? false : devToolsConfiguration
});

So they don't seem to be compatible at all. How can I write a action sanitizer for the actions now?


Upvotes: 0

Views: 234

Answers (1)

phry
phry

Reputation: 44086

Your action creators have a .match function:

actionSanitizer: (action: PayloadAction<any>) => {
    return someActionCreatorFromASlice.match(action)
    ? { ...action, payload: '<<LONG_BLOB>>' }
    : action

``

Upvotes: 0

Related Questions