1 min read

How to loop through data in Flows

Loop through data in Directus Flow using 2 flows and the Trigger Flow operation.

Sometimes we have an array of data to iterate through to perform actions. This article shows how to do this in Directus Flows.

To loop through data in Directus Flows, send the array of data to an operation known as "Trigger flow". This will run another flow for each item in the array. Create the action inside another flow and choose this as the triggered flow.

Step 1: Create a flow triggered by another flow

  1. Create a new flow that and set the trigger to "Triggered by another flow" and set the Response body to the Data of the last operation.
  2. Add the desired operations and use the data from the $trigger such as:
    • {{$trigger.collection}}
    • {{$trigger.key}}
    • {{$trigger.payload}}

Step 2: Create the main flow

  1. Create a new flow with the required collections and trigger.
  2. If you need to query data, use the "Read Data" operation with the following:
    1. collection set to {{$trigger.collection}}  (Event Hook) or {{$trigger.body.collection}} (Manual Trigger)
    2. IDs set to {{$trigger.keys}} (Event Hook) or {{$trigger.body.keys}} (Manual Trigger)
  3. Create a Script operation to transform that data into contextual payloads. Copy and paste the following where $last is the Read Data operation
module.exports = async function(data) {
	return Array.isArray(data['$last']) ? data['$last'].map((item) => {
    	return {
            collection: data['$trigger'].collection, // data['$trigger'].body.collection
            key: item.id,
            payload: item,
        };
    }) : [
      {
        collection: data['$trigger'].collection, // data['$trigger'].body.collection
        key: data['$last'].id,
        payload: data['$last'],
      }
    ];
}
  1. Create an operation that triggers another flow.
    • From the dropdown, cloose the flow created in step 1
    • Set the Iteration mode to serial (one after the other)
    • Set the Payload to {{$last}}

Conclusion

Now you have a flow that iterates over the array of data using 2 flows and the Trigger Flow operation. If you need to extend the scope of data, extend the script above to include or transform the data to the required format.

Send me a coffee

By continuing to use our website, you consent to use essential cookies. We also use optional tracking cookies which help us gather statistics to improve our services. Do you consent to these cookies?

I Consent Do not track