Reputation: 454
I'm facing a problem regarding the use of multiple thunk calls with each call depending on the previous state. Let me try to clarify the problem.
SPECIFICATION
I have a thunk that calls an API returning a list of items for a given accountID. This list needs to be iterated to find if a given item exists. If the element we're searching for doesn't belong to that list we need to do another API call with the next accountID. This process is repeated until, either the item is found or all the accountID's have been used.
CURRENT IMPLEMENTATION
Right now the current implementation is done using a thunk with the API call and once we get the response we filter the list. If the item is in the list we dispatch an action called 'ITEM_FOUND' otherwise we dispatch another action called 'NEXT_ACCOUNT'. This action increments an index stored in the Redux store. Then, in the componentDidUpdate we check if the index has reached the accountID length and if so we redirect to '/'. Otherwise, we call the thunk again.
Things I don't like about this solution:
I would like to improve the implementation to the best solution I can find.
Any ideas?
Upvotes: 0
Views: 410
Reputation: 19123
You should be able to put everything inside your thunk and avoid any unnecessary rendering, perhaps something like this (I am assuming ES6 syntax):
export const findItem = (ids, item) => {
return async (dispatch, getState) => {
try {
for (const id of ids) {
const items = await getItemsFromAPI(id)
if (items.find(i => i === item)) {
return dispatch('ITEM_FOUND')
}
}
} catch (e) {
// log error
}
}
}
You will note the use of the ES6 await
keyword to convert the multiple async API calls into an effectively synchronous sequence.
Upvotes: 1