PricingBlog

Repeated list should only display 1 random item

  • petershaw99-1246191260645982378

    PeterShaw

    1 year ago

    Hi toddlers, Assuming I have a list of 10 items which are repeated from my Supabase DB. In my UI I just want one of the 10 items being displayed, ideally randomly. I know in Weweb and Webflow you can limit and filter the repeated collections but I havent found a solution. Thank you:)
  • andreasmoller-1246192789612527669

    Andreas Møller

    1 year ago

    You can use something like this formula
    1246192789566521508-CleanShot_2024-05-31_at_22.04.412x.png
  • It generates a random number between 0 and the size of the array, and the extracts that item
  • andreasmoller-1246193231327137902

    Andreas Møller

    1 year ago

    If the list is small you could also do this.

    It sorts the array randomly and then gets the first item.
    1246193230840729610-CleanShot_2024-05-31_at_22.06.412x.png
  • The second option is simpler, but less performant, so it should not be used if you have a very large array
  • petershaw99-1246201850294964334

    PeterShaw

    1 year ago

    Thank you Andreas 🙂 When I am correct this is no longer a repeated list but youve created a variable containing the index of the items?
  • andreasmoller-1246202184065089719

    Andreas Møller

    1 year ago

    Yes, if you are only getting one element, you dont really need a repeated list, so you can just use a formula to get the random element.
    Just keep in mind that when a re-render occurs you will get a new element
  • If you only want to get the random element once, you should use a variable for holding the element, and then set it after the API response comes back. Does that make sense?
  • petershaw99-1246204437555577027

    PeterShaw

    1 year ago

    Thats what I had in mind. Add a button which will trigger rerendering so that a new item is displayed. I am stuck with getting the content from an API into a variable. It doesnt let me choose my API
    1246204437320564798-image.png
  • andreasmoller-1246225026454392883

    Andreas Møller

    1 year ago

    Are you setting the initial value of the formula?

    That wont work, because at that time the API would not have been called yet
    1246225026110455848-CleanShot_2024-06-01_at_00.12.552x.png
  • You have to use the success workflow in the api
  • 1246225203973853254-CleanShot_2024-06-01_at_00.13.462x.png
  • petershaw99-1246370641733488740

    PeterShaw

    1 year ago

    Great, that works. I added the formular and lastly I want to show the item as an output but it just says [object]. Do I have to add the formula to the text element itself or to the parent, too (as for repeated items).

    Thanks 🙂
  • andreasmoller-1246393069046337637

    Andreas Møller

    1 year ago

    You can use the Encode json formula is you want to print the data
    1
  • It use Get to extract individual properties