Nay Soewin
Nay Soewin

Reputation: 41

Listen certain redux action in components

Is there any way to listen certain action in component using redux-thunk middleware ? or do i really need to use redux-saga or redux-observable something to achieve this?

Here is my redux-thunk async action , i just simply want to close the dialog after TICKET_CREATE_SUCCESS action dispatched

export const createTicketEffects = (ticket: Ticket): ThunkAction<void, RootState, unknown, Action<string>> => {
    return async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
        dispatch(TicketActions.createTicket(ticket));
        return await TicketService.create(ticket)
            .then(({ data }) => {
                dispatch(TicketActions.createTicketSuccess(data.data, data.message));
            })
            .catch((error) => dispatch(TicketActions.createTicketError(error)));
    };
};

Thanks

Upvotes: 3

Views: 1254

Answers (1)

markerikson
markerikson

Reputation: 67627

Not in the sense you're asking, no. Components can't "listen for dispatched actions".

However, thunks can return a promise, and you can wait for that promise to be returned from dispatch(someThunk()):

Also, note that you can simplify that thunk using Redux Toolkit's createAsyncThunk API:

const createTicketEffects = createAsyncThunk(
  'tickets/createTickets',
  async (ticket: Ticket) => {
    const response = await TicketService.create(ticket);
    return res.data; // example: not sure what you're doing with `res.message`
  }
)

Upvotes: 4

Related Questions