LuisValgoi / ui5-webcomponents-react-seed

Seed of UI5 Web Components for React
12 stars 1 forks source link

Multiple Request being sent #28

Closed LuisValgoi closed 3 years ago

LuisValgoi commented 4 years ago

Reporter bug

https://github.com/tannerlinsley/react-query/issues/935

Branch

29

Screenshot

image

marceloschreiber commented 4 years ago

Cause

The first call is made by RouteValidator:

<RouteValidator
  allowedAuthorities={['canAccessTodoListPage']}
  authorityKey='permissions'
  path={BrowserURL.TODO_LIST}
  component={TodoList} />

Second one is made by TodoList:

<ComponentValidator
  allowedAuthorities={['canAccessDropApplication']}
  authorityKey='permissions'>
  <CenteredLink text='Drop Application (this is a restricted text and you should not see unless you have access)' /> 
 </ComponentValidator>

Solution

Since permissions are something that does not change often I don't think it's a good idea to call the backend every time that the frontend needs to perform this check.

The simplest solution to achieve this would be to use the react-query cache, this can be done by setting the staleTime property of the useQuery hook. Refer to the documentation

useRequest.js:

///...
const FIVE_MINUTES_IN_MILLISECONDS = 1000 * 60 * 5;

function useOperation(reactQueryKey, operation, urlKey, dataParam, config) {
  const { data, status } = useQuery(reactQueryKey, async () => {
    const url = UrlProvider.getUrl(urlKey);
    const res = await Request[operation](url, dataParam, config);
    return res.data;
  }, {
    staleTime: FIVE_MINUTES_IN_MILLISECONDS
  });

  return { data, status };
/// ....
}

This way the next calls withing the 5 minutes mark are going to be retrieved from the cache.

LuisValgoi commented 4 years ago

Awesome @marceloschreiber Really thanks for that!