Using Data in Stimulus
This lesson will show how to use data with Stimulus.
We'll cover the following...
With async
, await
, and fetch
in our toolbox, we can get our Stimulus controller to contact the server to get data about which concerts are sold out. We could also do this with Turbo Streams, but for the moment let’s assume we’re locked into an existing API for the sold-out data. Let’s also assume for the moment that we need to get continuous data and that we’re choosing to do this by polling the server continuously for updates. Later, we’ll look at how to use ActionCable for server push.
Sold-out concerts controller
On the Rails side, we’d like to set this up as its own route by adding a new singular resource to the routes.rb
file:
Rails.application.routes.draw doresources(:favorites)resource(:schedule)resources(:shopping_carts)resources(:ticket_orders)resources(:tickets)resources(:gigs)resources(:concerts)resources(:bands)resources(:venues)# START_HIGHLIGHTresource(:sold_out_concerts, only: :show)# END_HIGHLIGHTdevise_for(:users)root(to: "schedules#show")end
This lets us put the API code in a new controller, which is good both from a conceptual standpoint, as it’s a completely different kind of request, and from a practical standpoint, because it might be easier to separate into a designated service later on as it is its own route.
Here’s what that API controller looks like:
#---# Excerpted from "Modern Front-End Development for Rails",# published by The Pragmatic Bookshelf.# Copyrights apply to this code. It may not be used to create training material,# courses, books, articles, and the like. Contact us if you are in doubt.# We make no guarantees that this code is fit for any purpose.# Visit http://www.pragmaticprogrammer.com/titles/nrclient for more book information.#---class SoldOutConcertsController < ApplicationControllerdef showconcerts = Concert.includes(:venue, gigs: :band).allsold_out_concert_ids = concerts.select(&:sold_out?).map(&:id)render(json: {sold_out_concert_ids: sold_out_concert_ids})endend
Here, we’re returning a JSON file to be parsed on the client with the IDs of all the sold-out ...