React and Action Cable
Use React and Action Cable in this lesson.
We'll cover the following...
Currently, our concert show page makes a fetch call to the server to determine the current status of the seats on the page, and it makes a POST call to put a seat on hold after you click on it. We can replace both of these calls with a single Action Cable subscription. Granting, of course, that this is an absurdly minimalist implementation, since we’re not dealing with user logins or complicated state transitions or anything like that.
ConcertChannel
on the server
On the server-side, we need to create a new Action Cable channel. This one will have the same subscribe
method as our previous channel, but we need to add a method for our client-side to call to actually reserve a ticket:
#---# 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 ConcertChannel < ApplicationCable::Channeldef subscribedstream_from("concert_#{params[:concertId]}")enddef unsubscribed# Any cleanup needed when channel is unsubscribedenddef added_to_cart(data)workflow = AddTicketsToCart.new(concert_id: data["concertId"],row: data["row"],seat_number: data["seatNumber"],tickets_to_buy: data["ticketsToBuy"],status: data["status"])workflow.runresult = Ticket.grouped_for_concert(data["concertId"])ActionCable.server.broadcast("concert_#{data["concertId"]}", result)endend
This code includes two changes from our earlier channel. In the subscribed
method, our stream_from
name is now a dynamic string: concert_#{params[:concert_id]}"
. This suggests two things. First, it means that different concerts will have different streams, so we don’t have to worry on the client about seeing messages not meant for the page we are on. It also means that the client will need to pass the concert id as a parameter when it subscribes.
And you probably noticed the ...