React and ActionCable

This lesson will explore how to use React and ActionCable.

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. It also makes a POST call to put a seat on hold after we click on it. We can replace both these calls with a single ActionCable subscription. This is a minimalist security setup, but we’ll keep it simple for the purposes of this course.

ConcertChannel on the server

On the server-side, we need to create a new ActionCable 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 reserve a ticket:

Press + to interact
class ConcertChannel < ApplicationCable::Channel
def subscribed
stream_from("concert_#{params[:concertId]}")
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def added_to_cart(data)
cart = ShoppingCart.find_or_create_by(user_id: data["userId"])
cart.add_tickets(
concert_id: data["concertId"],
row: data["row"],
seat_number: data["seatNumber"],
tickets_to_buy_count: data["ticketsToBuyCount"],
status: data["status"]
)
result = Ticket.grouped_for_concert(data["concertId"])
ActionCable.server.broadcast("concert_#{data["concertId"]}", result)
end
end

This is more complicated than 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 needn’t worry about the client 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.

Notice, also, the added_to_cart method. This method is called when the client sends a message that tickets are to be added to the cart. It combines the functionality we put in the ShoppingCartsController to update tickets and the functionality we had in TicketsController to return a data structure of all the tickets sorted by row. That functionality has been refactored into ...