Setting the value of state using function setValue()



This is not returning Hello world the new value I set. Rather it is returning the old value.
how can i make sure the value is set before the execution of next line?

I also tried this way

async function updateAndUseVariable() {
  await state.setValue('hello world')
  return state.value
}

return await updateAndUseVariable();

but this is also not working.
It is still returning Initial state.

Why there is delay in setting the value of state?

1 Like

Hi there @engineering-tajir,

My first question is, why would you access the variable's value is you already have it? You could create a constable with the same value you used to set the value of the variable. Just trying to understand your use case.

In any case, lacking the words to explain it myself, here's what an llm has to say about it:

In Retool, state.setValue() (and similar .setValue() calls on temporary state variables) is asynchronous and does not immediately update the .value property. Even using await won't help because .setValue() is not a Promise-based APIβ€”it triggers a change, but state.value won't reflect the new value until the next tick of the app's state system (UI reactivity loop).

There is an action on which I need to trigger multiple queries. These queries use a state. I just want to make sure the state is set to new value before the queries use it

Just created a simple scenario to understand how retool set the value of state. Is it an asynchronous operation or synchronous? I tried both ways, but unable to draw a conclusion

Got it. It is asynchronous. I believe.

However, I think that for your use case, you can use additionalScope to pass the values to the queries you're triggering.

Or am I understanding this incorrectly?

Hey @engineering-tajir! Thanks for reaching out. I run into this fairly often and the solution is very subtle. While it's true that setValue acts asynchronously, it is Promise-based and respects await. The issue is that Retool closes over the value of certain state variables during the execution of JS scripts in order to improve performance.

If you need to both write to and read from a variable within a single code block, you can disable this default behavior via the query's Advanced settings.

I hope that helps! Let me know if you have any questions.

1 Like