Steven G
Steven G

Reputation: 17122

How to get the action type from redux toolkit

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?

Upvotes: 6

Views: 5938

Answers (1)

markerikson
markerikson

Reputation: 67489

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
}

Upvotes: 4

Related Questions