0

I have a redux store containing multiple states which is populated by same api but multiple end-points.

I have a react app with multiple components, which access to one of these states, and they all call to the correspondent api no mount by dispatching a async function (redux-thunk) to the store.

In the App.js multiple components are used.

Problem: When all the components mount they call to the api concurrently and exceeds the maximum number of call allowed for the short time frame. Thus all calls reply with status code 429: Too many request.

*Extra notes: I'm buliding a news web-app, and using gnews.io api with multiple search queries and end-points to get data.

1 Answers1

0

In your case i believe one approach would be to create a request type and use it in your state instead of the raw value returned from the endpoint, something like:

type TApiRequestState<T> = {pending: boolean, response: T}

When you dispatch an action that will trigger the endpoint in thunks you would set the api state to loading. After that all you need to do is check if the request is not already running on the other components.

if (!value.pending && !value.response) {
   dispatch(thunksFn)
}

In theory you could dispatch all of the initial requests on a parent component and only render these child components when the initial requests are done. But this depends on a project to project basis IMO.

Breno Prata
  • 712
  • 5
  • 10
  • For this case, first api function will be dispatched and pending will be turned true. By the time pending will be turned false during that time other dispatch call will not be executed for if statment. And those unexecuted dispatch call will never be called latter in this approach. – Priyabrata Chattaraj Jun 17 '22 at 10:33
  • And it'll will be good if can answer in javascript code not typescript. I not well versed with typescript. – Priyabrata Chattaraj Jun 17 '22 at 10:34
  • The same logic applies to JS, you would have to save object: `{pending: true}` -> `{pending: false, response: {}}`. – Breno Prata Jun 17 '22 at 10:37
  • Also what I was thinking if I can pause that api call, push api calls in call stack like and wait for the fish and then pop until empty for every request. I'm not saying I only want this approach, there might be better solutions. – Priyabrata Chattaraj Jun 17 '22 at 10:42
  • Here unexecuted dispatch calls will not be called ever. – Priyabrata Chattaraj Jun 17 '22 at 10:45