State variables
Last updated
Last updated
State variables function as temporary storage while users interact with your app. They reset to their initial values upon a page refresh or when the app is closed.
For persistent storage that remains intact upon page reloads, consider exploring Local storage.
State variables come in two scopes:
App - maintain their values across different pages
Page - maintain their values only within a specific page
State variables can possess the following attributes:
Name - the unique identifier
Type
String
Number
Boolean
Object
Arrray
Initial value - the starting value of the variable
State variables can be organized using the folder structure of the Actions panel, allowing you to place relevant variables near the actions and logic they are associated with.
You can create a state variable, same as you would create an Action, from the Actions panel. You just need to click the plus sign and select State variable. From there, specify your variable type, assign it an initial value, and give the variable a meaningful name.
That's it! You can now read and write to this variable. Depending on its scope, it will be available either in the whole app or on a particular page.
Now that you've created a state variable, let's explore how you can use it in your app. Within the app, all variables can be accessed using the {{state.<variableName>}}
scope.
You can also assign a value to a variable using the Save to State action or directly through JavaScript code blocks. Check out the sections below for more details 👇
To store a value within an action, follow these steps:
Add a new step to your action and select Save to State.
Select the variable you want to modify.
Define a new value for the variable, which can either be hardcoded or derived from an available variable.
For example,{{data}}
to reference the result of a previous action step, or {{ui.component.value}}
to access a component's state.
You can use state variables in JavaScript code blocks to:
Save state values
Read with the state.getValue
method
Reset a single variable or all variables to the initial value
Let's review an example of resetting a state variable value - you have a Text input component and you would like it to reset its value after a comment is left.
Here's how you can do that:
Create a state variable of the String type, define its initial value, and name it Comment, for example.
Assign the variable to the Text input component's Value field.
Create a Save to State action that will save the new comment - define its value as {{data}}
.
Assign this action to the On Change trigger of the Text input component.
Next, create another Save to State action, that will reset the comment - define its value as ''
.
Now, add a Button component to the working area and assign the Reset action to its On Click trigger.
Done! Now, after you leave a comment and click the button, the component will reset its value.