Using Data in Stimulus
Learn to use data with Stimulus in this lesson.
We'll cover the following...
With async
, await
, and fetch
in our toolbox, we can get our Stimulus controller to contact the server directly to get the information about which concerts are sold out.
Sold-out concerts controller
On the Rails side, I’d like to set this up as its own route by adding a new singular resource to the routes.rb
file:
Press + to interact
#---# 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.#---Rails.application.routes.draw doresource :scheduleresources :ticket_ordersresources :ticketsresources :gigsresources :concertsresources :bandsresources :venuesresource :sold_out_concerts, only: :showdevise_for :usersroot to: "schedules#show"end
This lets us put the API code in a new controller, which is good both from a conceptual standpoint—it’s a completely different kind of request—and from a practical standpoint—as its own route, it might be easier to separate into a designated server later on.
The controller is similar to what were were sending earlier in this chapter via Gon:
Press + to interact
#---# 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
We’re returning a JSON file to be parsed on ...