Can REST API queries that are run on page load wait for some variables?

  • Goal: Automatic-run REST API queries should be able to wait for their dependencies before running.

  • Steps:

  1. I have a bunch of queries that are run on page load to get some resources from an external API server.
  2. The external API server protects its routes via JWT tokens (standard access tokens)
  3. On page load, my app will also ask for the access token. My REST API queries add this token to their Authorization headers (hence these queries DEPEND on the access token)
  4. However, the access token query takes < 1 second (but not synchronous). The other REST API scripts run on the same page load as well, returning a bunch of 403 errors as expected. Only after the access token resolves, then the same scripts will rerun since their dependency (the token) has updated. Only then will these queries be resolved properly.

My question is:

  • Is it possible to intercept and block execution of queries if the access token is undefined/empty?

Please do not suggest running ALL of these scripts in the success handler of the access token request. That isn't optimal user experience.

Can you explain the difference between:

having a bunch of queries depend on something, but block and have them run the query to get the token...

VS

Calling said query first, and get the token, and feed to the others?

Wouldn't both solutions, produce the same timeline of resources being fetched? Either way, the fetching of the token, must come first, so why not have it start the chain? You could definitely store the token temporarily and check if it is expired so that it is not always called first.

I don't quite understand how utilizing the onSuccess callback and then triggering the other API queries, would result in a poor user experience.

Hi @Joel_Tay, welcome to the forum! :wave:

If we don't want to use success event handlers for all other queries, we could set up a flag using a State variable with a default value of false, and disable the queries conditionally based on that value.

For example, let's imagine that query1 and query2 are the resource queries we need to run after the getToken REST API query is successful.

Under advanced settings for the queries, we can add a condition to disable them (Disable query):

Note: Although they are set to run on page load, they won't until the flag changes to true.

Finally, we can set up a single success event handler to the getToken REST API query to set the value of flag to true:

In action:


Note: I set the getToken query to run manually to show that the other queries are not running yet.

After running getToken, they run and populate the app with data: