Masoud92m
Masoud92m

Reputation: 622

how to dispatch a action in redux middleware?

I wrote a middleware, like as blow :

const testMiddleware = ({ dispatch, getState }) => next => action => {
    console.log('test middleware')
};

export default testMiddleware;

and added it to my store: applyMiddleware(testMiddleware) in ever action, i get test middleware in my console.

and i wrote a simple action, like this:

export const sayHi = () => {
    return dispatch => {
        console.log('hi');
    }
}

How can i dispatch sayHi action in my middleware?

Upvotes: 1

Views: 2167

Answers (1)

IfSoGirl
IfSoGirl

Reputation: 161

Middleware gets the store’s getState() and dispatch() functions as first argument, so you can do the following (after importing required actions):

const middleware = ({dispatch, getState }) =>{
    return next => action => {
        dispatch(someAction);
        // return data;
        return next(action);
  }
}

So, the middleware signature is ({ getState, dispatch }) => next => action.

https://redux.js.org/api/applymiddleware

Upvotes: 3

Related Questions