How to get the action type from redux toolkit

Viewed 2503

I created a Slice using createSlice from redux toolkit and exported my action such as:

export const { myAction } = slice.actions;

I am trying to create a middleware to catch some action type:

import myAction from './reducers/mySlice'

const MyMiddleware = store => next => action => {
  if (action.type === myAction.type) {   //this doesn't work, myAction is a function
    doSomething(action.payload);
  }
   return next(action);
};

I was wondering if it was possible to get the action type as a constant from the slice I created?

1 Answers

Your import statement is wrong. You're doing a named export (export {myAction}), but a default import (import myAction).

Change it to import {myAction} from './reducers/mySlice', and that middleware could should work.

Action creators also have a .match() function attached that you can use:

if(myAction.match(action)) {
  // logic here
}
Related