It can't be this hard, right? I must be doing something wrong

I have a multi-page app. Let's call page 1 Table and page 2 Form. At the top of the Table page I have a Create button that launches me over to the Form. I am trying to set a variable (call it varCurrentRecord) to my ID from my Retool Database table.

I have tried this 100 ways and just couldn't get varCurrentRecord to populate. I landed on triggering the following JS Query on page load under certain conditions:

console.log("hit script");

// Run `qCreateNewPlan` and wait for results
try {
  const plan = await new Promise((resolve, reject) => {
    qCreateNewPlan.trigger({
      onSuccess: (data) => {
        resolve(data);
      },
      onFailure: (error) => {
        console.error("Error triggering qCreateNewPlan:", error);
        reject(error);
      },
    });
  });

  console.log("Plan result:", plan);

  // Check and process the result
  if (plan.result && plan.result.length > 0) {
    const planId = plan.result[0].id;
    console.log("Plan ID:", planId);

    // Set `varCurrentRecord` to the plan ID
    await varCurrentRecord.setValue(planId);
    console.log("varCurrentRecord updated to:", varCurrentRecord.value);
  } else {
    console.error("No results found in plan.result.");
  }
} catch (error) {
  console.error("An unknown error occurred:", error);
}

console.log("Script complete.");

Where qCreateNewPlan submits an insert to my database. Please tell me there's an easier way?

Depending on the set-up few things might be wrong here:

  • is the qCreateNewPlan on global scope, if it isn't switching pages clears out results
  • same question applies for the variable
  • Have you tried on success of qCreateNewPlan opening page2 with url or hash param that contains an id - this should significantly simplify the logic and cut out the need for variable/complex logic

I.e. you trigger qCreateNewPlan on failure handler just add an error on success just navigate to a different page with param and no JS is needed.

Hope this helps!

Thanks for this - I tried it in global and it did not work. The URL parameter makes more sense. I was running short on time last night and didn't want to have to rewrite all of my queries. I'm going to go that route - it would make life so much easier.

1 Like