What is a good way to delay api call?

Viewed 3395

In my app (React + Redux + axios + redux-thunk + Typescript) I have a situation when I do API call, change item in database and show current, changed state in table. 
So, it looks like:

const changeItem = () => changeItemState(item.id).then(getItem(item.id));

Both actions (changeItemState and getItem) are imported from reducer file. 
The problem is, changing item process, on the back-end site, takes too long. So, I reload table (call api to get item - getItem(item.id)) but the backend changing process is still ongoing, so I receive old state. After 100-300 milliseconds I can query item again (refresh page for example) and get new state of item. But I don't want to do it manually. I want to reload table after back-end prepared my item to show with new state.

The question is - how to delay get item action? Are there any front-end patterns for this? I would like to avoid use “setTimeout()” method like this (imo it’s not an ideal solution):

const changeItem = () => changeItemState(item.id).then(setTimeout(function(){ getItem(item.id); }, 300));,

2 Answers

You can promisify setTimeout like this:

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

Then,

const changeItem = () =>
  changeItemState(item.id)
    .then(() => delay(300))
    .then(() => getItem(item.id));

or equivalently with an async function

const changeItem = async () => {
  await changeItemState(item.id);
  await delay(item.id);
  return getItem(item.id);
}

Well, there is no elegant solution if you are not using Websocket (https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API)

The only way you can is to have those setTimeout delays and compare old data with new. That is the best you can do.

But if you go with Websockets route, you can have realtime communication from BE and it will emit changes and you app will react to those changes.

This will require you to do refactoring on BE to support Websockets.

Good luck!

Related