How to loop through data in Flows
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
- 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.
- 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
- Create a new flow with the required collections and trigger.
- If you need to query data, use the "Read Data" operation with the following:
- collection set to
{{$trigger.collection}}
(Event Hook) or{{$trigger.body.collection}}
(Manual Trigger) - IDs set to
{{$trigger.keys}}
(Event Hook) or{{$trigger.body.keys}}
(Manual Trigger)
- collection set to
- 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'],
}
];
}
- 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.