Using Gon in Stimulus
Explore how to integrate Gon with Stimulus in a Rails application to efficiently transfer server data to the client-side. Understand managing unstructured global variables with TypeScript, setting up controllers with data values and targets, and enhancing responsive UI updates without extra Ajax calls.
We'll cover the following...
Building up a controller
Now we can use the JavaScript global variable, which has the contents of our gon item, in our code by building up a Stimulus controller that reads from it. We need to add a little extra code to make sure TypeScript is okay with an unstructured global variable, since TypeScript is normally all about not being okay with unstructured global variables.
In Stimulus terms, we want a controller that will have one value (the id of the concert) and one target (the text that currently says “On Sale”). That’s three changes to the existing ERb file in app/views/schedules/show.html.erb. In keeping with the idea that Stimulus controllers should cover as little of the page as possible, we’ll set this one up inside the loop ...