Variable setValue to Dynamically Trigger Resources

  • Goal:

Can execute a resource connected to our API with a dynamic JSON body.

  • Steps:

I have our Resource, which is connected to our API, and the JSON body is correctly setup. I have tested this in different apps and environments, and the query is good to go.

  • Details:

Inside of the JSON body, we have one variable currentUser where currentValue.value = correct email.

Given an array, a, containing the full list of emails, I iterate through each email and trigger the query with the variable set as the current user email.

a.forEach((email) => {
    currentUser.setValue(email)
    query1.trigger();
    console.log(currentUser.value)
  })

Unfortunately, this seems to only console.log() the last email within the array.

Similarly, when I check out logs of our API, I only see it being called with the last email within the array.

Since we are using a custom resource, it appears the additionalScope is not available/recognized here (whereas, when we use a Postgres query to get the list of emails we have the option to use additionalScope, which is working as expected).

I'm looking for alternative solutions such that we can dynamically update the body of the resource query while still iterating the list of arrays.

Could you create a variable (vUserEmail or whatever), reference that in the body of the API, and in the code, do something like:

a.forEach((email) => {
    vUserEmail.setValue(email)
    console.log(vUserEmail.value) // just to check
    query1.trigger();  // vUserEmail will be used in the body of query1
  })

Hi @jg80, yes, currentUser is the variable.

If we assume something like...
a = [ 'email@a.com', 'email@b.com', 'email@c.com' ]

Running the block of code:

a.forEach((email) => {
    currentUser.setValue(email)
    console.log(currentUser.value)
    query1.trigger();  
  })

The output looks like:

email@c.com
email@c.com
email@c.com

And our (internal) logs that are produced when query1 is fired contain the same email in the body requests.

I think this is a synchronous vs. asynchronous processing thing, and I always have a heck of a time working those out...I can make the following work, faking your API as a query that logs the email to the console:

async function processEmails(emails) {
    for (const email of emails) {
        await currentUser.setValue(email);
        await fakeAPI.trigger();
    }
}

let a = [ 'email@a.com', 'email@b.com', 'email@c.com' ];
processEmails(a);

I get the following:

I'm sure someone here (maybe you!) can explain the details far better than I...I just know that this is a setup I've resorted to in the past for similar things, so maybe it will help here too.