Reputation: 167
I'm quite new to Typescript and I'm trying to dispatch two API calls to a database. The second one should only run once the first one is resolved. The solution should work with Redux-Thunk (not Redux Saga). I have tried async/await and promises without success. I couldn't find any useful answeres in other posts.
First Action
private placeOrder(addressId?: number, projectId?: number) {
this.props.dispatch(
requestAPIActions.load<RequestApiHttpPayload>('order', {
url: '/orders/place-order?addressId=' + addressId + '&projectId=' + projectId,
queryType: false,
options: {
method: 'POST',
}
})
);
}
Second Action
private deleteGuest(id: number) {
this.props.dispatch(
requestAPIActions.load<RequestApiHttpPayload>('client', {
url: `/clients/${id}`,
queryType: false,
options: {
method: 'DELETE',
}
}));
}
Edit
requestAPIActions.load is:
declare const requestAPIActions: {
LOAD_REQUEST: string;
/**
* Redux action to dispatch the initial request to the URL and
* by using the given config.
* @alias requestAPIActions.load
* @param {String} requestId Id that describes the dispached request
* @param {Object} payload Url and Config for Axios promise
* @returns {Object} FSA<string, {}, RequestApiMeta>
*/
load<Payload>(requestId: string, payload: Payload, update?: boolean): import("flux-standard-action").FluxStandardAction<string, {}, RequestApiMeta>;
This is where I start to loose understanding of what exactly is happening.
Upvotes: 0
Views: 136
Reputation: 4176
I think the solution would be to dispatch the second action in the then
block of the first.
Here is an example from the redux-thunk docs:
// Meet thunks.
// A thunk in this context is a function that can be dispatched to perform async
// activity and can dispatch actions and read state.
// This is an action creator that returns a thunk:
function makeASandwichWithSecretSauce(forPerson) {
// We can invert control here by returning a function - the "thunk".
// When this function is passed to `dispatch`, the thunk middleware will intercept it,
// and call it with `dispatch` and `getState` as arguments.
// This gives the thunk function the ability to run some logic, and still interact with the store.
return function(dispatch) {
return fetchSecretSauce().then(
(sauce) => dispatch(makeASandwich(forPerson, sauce)),
(error) => dispatch(apologize('The Sandwich Shop', forPerson, error)),
);
};
}
// Thunk middleware lets me dispatch thunk async actions
// as if they were actions!
store.dispatch(makeASandwichWithSecretSauce('Me'));
Upvotes: 1
Reputation: 444
if both actions are a promise why don't you just run
Promise.all([dispatch(action1(), dispatch(action2()])
.then(([res1,res2]) => console.log(res1,res2)
Upvotes: 0