import { createListenerMiddleware, isRejected } from '@reduxjs/toolkit';
import message from 'antd/lib/message';

const rejectedErrorHandlerMiddleware = createListenerMiddleware();

rejectedErrorHandlerMiddleware.startListening({
  predicate: isRejected,
  effect: async (action, listenerApi) => {
    listenerApi.cancelActiveListeners();
    await listenerApi.delay(100);

    if (action?.payload?.message) {
      message.error(action?.payload?.message);
    } else if (action?.error) {
      message.error((action)?.error?.message);
    }
    console.error(`Redux Rejection Error | `, action);
  },
});

export default rejectedErrorHandlerMiddleware;
