After completing the section Using Data in Stimulus (ends pg 167), I noticed something wrong with Ajax updates. After running the rake task to sell out concerts, things looked fine on initial browser load:
but after Ajax it would change from “Sold Out” to “0 Tickets Remaining”:
The data attributes looked like this:
So concertSoldOutValue
was suspiciously being set to false
. The issue is that Array#includes
is called with a string on an array of numbers (always false
):
concertElement.dataset.concertSoldOutValue = soldOutConcertIds.includes(
concertElement.dataset.concertIdValue
)
typeof soldOutConcertIds[0]: number
The ids coming from the server JSON are numbers. One solution is to convert the ids to a string:
class SoldOutConcertsController < ApplicationController
def show
concerts = Concert.includes(:venue, gigs: :band).all
sold_out_concert_ids = concerts
.select(&:sold_out?)
.map(&:id)
.map(&:to_s)
render(json: {sold_out_concert_ids: sold_out_concert_ids})
end
end
Perhaps TypeScript could be leveraged to prevent this kind of bug?