Let's Add A Collection
In our previous video, we used a Data Source element to connect to an API endpoint. We got a Response that we mapped to a text field and an image...
But we only received one JSON object of key/value pairs in our response.
Very often from an API we end up with what’s called an Array of Objects in a Response. An Array is a collection of elements. So for example instead of a fruit, we have an array of fruits.
Working With An Array in Judo
The Collection element is how we iterate through an Array that's in our Response from our API.
For this example, here's the beginnings of a simple experience that shows us the weather for Toronto.
We’ve already added a Data Source element that’s connected to a real simple weather API. Our temperature, wind speed and weather description text fields are already hooked up and live.
But, our Forecast section in our Response is what we’ll need a Collection for.
One particular key in our JSON Response is called “Forecast”, and in this case, the value for Forecast is an array, which we can tell because Arrays are surrounded by square brackets.
We want to render the temperature and wind for each of these 3 days. When working with data in an array, and we want to do the same thing for each result, we call that iterating through our data.
To iterate means to perform repeatedly. This is similar to a programmer using a “for each” loop.
In Judo, we use a Collection element to Iterate or loop through an Array in our response.
Let's add a Collection element making sure it’s nested somewhere beneath our Data Source.
Then, in our Collection settings, we type “data.” and then the name of the Array we’d like to iterate over. In our case here, it’s “data.forecast”.
Render For Each
Now we want something to render for each item in our array.
All we do is drag something under our Collection, as long as it is properly mapped to the Array in our Response, and Judo will render the immediately nested layer once for each item in our Array.
Then we map the values just like with a single-response Data Source.
For example in a text field, we type two curly braces, and as long as our Collection is mapped properly to our Array, we will see our auto-suggested options.
If we map Temperature as well as wind, we should now see 3 rendered text fields with the temperature for the next 3 days:
Reminder Make sure "data." comes before the name of the key we want to work with in our Text or Image fields
On a Collection, we can add a Filter which is most commonly used on “Is Set”, so as to filter out any results that are null. Handy for large Data Sources.
We can also Sort like so, where we’ve reversed the Days.
And lastly we can Limit our results, and also specify the Index we want to start at.
Great work, next up is Conditionals.