Build a Simple LiveView
Explore how to build a simple LiveView in Phoenix by defining routes, rendering dynamic pages with templates, and handling events through WebSocket communication. This lesson guides you in creating a number guessing game that demonstrates foundational real-time interface concepts using LiveView.
We'll cover the following...
The Pento app’s first LiveView will be a simple game called “You’re Wrong!”. It will ask the users to guess a number and then tell them they’re wrong.
We’ll have to do three things:
- Build a route
- Render a page
- Handle the events
Let’s go!
How to define the route
LiveView routes are defined in our Phoenix application’s router. First, we open up lib/pento_web/router.ex and add the live route for "/guess" like this:
We set up everything in the code below. The results can be viewed just by running it.
Most Phoenix route definitions use HTTP methods, primarily get and post. A LiveView route is a little different. Live view routes are defined with a call to the live macro (more on that later) and point to a long-running LiveView. The initial HTTP request and response will flow through this route. After that, the WebSocket will handle the communication.
How to render the LiveView
Let’s shift to the code that implements our LiveView. We created a new file inside lib/pento_web/live called wrong_live.ex.
These concepts are foundational, so we’ll address them in three parts.
First, we define the live_view module in the lib/pento_web/liv/wrong_live.ex file ...