Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chaining redux-actions and redux-promise-middleware

I use redux-actions and redux-promise-middleware to dispatch actions, along with TypeScript 2.1 for async await support.

This is an action using both redux-actions and redux-promise-middleware

// create an async action
const fooAction = createAction('FOO', async () => {
  const { response } = await asyncFoo();
  return response;
});

// use async action
fooAction('123')

And this is an example of action chaining, using only redux-promise-middleware

const foo = () => dispatch => {
  return dispatch({
    type: 'TYPE',
    payload: new Promise()
  })
  .then(() => dispatch(bar()));
}

How chaining in redux-promise-middleware can be used together with redux-actions?

like image 201
Rajab Shakirov Avatar asked Dec 28 '16 17:12

Rajab Shakirov


People also ask

What is Redux promise middleware?

Redux Promise Middleware enables simple, yet robust handling of async action creators in Redux. const asyncAction = () => ({ type: 'PROMISE', payload: new Promise(...), })

Is Redux synchronous or asynchronous?

Redux Middleware and Side Effects​ By itself, a Redux store doesn't know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer function, and notify the UI that something has changed. Any asynchronicity has to happen outside the store.

How do you handle async actions in Redux?

Using Thunk and Redux Toolkit to manage asynchronous actions The role of this middleware is very simple: verify if an action is a function and, if it is, execute it. This simple behavior allows us to create actions not as simple objects, but as functions that have business logic.

What does Redux promise do?

redux-promise "teaches" dispatch how to accept promises, by intercepting the promise and dispatching actions when the promise resolves or rejects. Normally, dispatch returns whatever action object was passed in. Because middleware wrap around dispatch , they can also change what value is being returned.


1 Answers

You have to keep in mind that even if async await looks synchronous, it uses Promises under the hood, and an async function will always return a Promise, no matter if you use await or not.

Since the second parameter of createAction is your payload creator, nothing can stop you from using the resulting object.

Here is an example based on your initial code:

const fakeCall = () => new Promise(resolve => {
  setTimeout(() => resolve({ response: 'ok' }), 1E3)
})

const fooAction = createAction('FOO', async () => {
  const { response } = await fakeCall()
  return response
})

const foo = () => dispatch =>
  dispatch(fooAction())
    .then(() => dispatch(bar()))

// or

const foo = () => async dispatch => {
  await dispatch(fooAction())
  dispatch(bar())
}
like image 121
Preview Avatar answered Oct 02 '22 17:10

Preview