Looping is a fundamental concept in programming that allows you to iterate through repetitive tasks, transform elements in an array, and more. In Xano, you can find loop functions under the "Data Manipulation" > "Loops" section. Let's explore the three main loop options available: for loop, forEach loop, and while loop.
for LoopThe for loop is typically used when you want to create a list of items, and you already know the predetermined number of iterations. Here's an example of generating 10 unique IDs and adding records to a table:
for loop function.start value to 1 and the end value to 10.uuid() function.After running the task, you should see 10 new records added to the "loops" table, each with a unique ID in the "feud" field.
forEach LoopThe forEach loop iterates over each item in a list, repeating the loop for the total number of elements in the array. To use a forEach loop, you need to have an array first. Let's walk through an example of updating a field for each state in the US:
forEach loop function and set the list input to the variable containing the query results (e.g., us_states1).item variable to represent each element of the list.item.id as the field value.true to mark the record as updated.After running the task, you should see all records in the "US states" table updated with the changes you made inside the forEach loop.
For working with large lists (e.g., 30,000+ records), it's recommended to use the stream output type for the query, as it works well with forEach loops and prevents straining server memory.
while LoopThe while loop is used when you don't know the number of iterations beforehand, making it ideal for working with paginated data from external API requests. The loop repeats as long as a specific expression is true. Here's an example of breaking the loop under different conditions:
while loop function with the condition set to true === true (always true).random() function.break function.debug_log() function for visualization.You'll notice that the loop continues until the random number generated is 10, at which point it breaks out of the loop.
Alternatively, you can use a variable to control the loop condition:
number with an initial value of 0.while loop function with the condition set to number !== 10 (loop until number is not equal to 10).number variable with this value.debug_log() function for visualization.The loop will continue until the number variable becomes 10, at which point it breaks out of the loop.
Remember, it's crucial to have a condition to break out of a while loop, or you'll end up with an infinite loop.
By mastering these loop options in Xano, you'll be able to iterate through arrays, make transformations, and automate repetitive tasks more efficiently. Don't hesitate to leave comments below if you have any questions or need further assistance!
Join 100,000+ people already building with Xano.
Start today and scale to millions.