skip to Main Content

I have a large application, where I use redux to store my fetched data. Each component that needs data ensures it will get what it needs by running request and waits for the data to appear in
useSelector(state => state.dataReducer.data).

In most simple use it is ok, but when two components on the same page require same data, they both run fetching

My solution is (code simplified, I tried many ways of accessing store)

if(store.getState().requests.hasOwnProperty(url)) {
   return false
}

store.dispatch(setRequest(url));

get(url).finally(() => {
   store.dispatch(unsetRequest(dataKey));});
})

Unfortunately, async store update do not perform its operations when I need them to be performed, and when 2 simultaneous requests run, state has not been updated yet.

For testing purposes, I run the other request with timeout of 200ms and it is OK, but in normal application context, it’s not possible.
How to prevent this?

2

Answers


  1. This is a common problem.
    There will be a lot of ways to do it but the general idea should be that your store should be aware that a similar API call is already in-flight. You can save lifecycle states such as loading | loaded | null and so on for every URL + method + (data/queryParams) combo. Check this state before making any API call.

    The above you might be able to do using some hashmap. But a custom implementation for such a general problem is not required.
    redux-saga, redux-thunk might be of help. react-query should also be useful

    Login or Signup to reply.
  2. These 3 libraries solve your problem:

    Pick the one that aligns the best for your project.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search