I will assume that you have Elixir 1.14 installed. We are going to be using Phoenix version 1.7 in this tutorial. To install it, run the following command in your terminal:
mix archive.install hex phx_new
You may need to uninstall your previous version first (if you had it installed already):
mix archive.uninstall phx_new
Creating the App
Great! Now, let’s begin our Phoenix project by using the
mix phx.new command:
mix phx.new todo
Great! Now let’s
cd into the new
todo directory and run the following commands:
Great! That created the initial PostgreSQL database for us. Now, let’s run the following command to make sure everything was set up correctly:
iex -S mix phx.server
Now browse to
localhost:4000 and you should see the Phoenix welcome page. If not, you will need to debug the reason you are getting your specific error.
Creating the Todos
First, let’s take a look at the help dialog that ships with Phoenix by running the following command:
mix help phx.gen.live
Feel free to read this at your convenience. Now, let’s create the Todos using the following command:
mix phx.gen.live Items TodoItem todo_items text:string
Next, follow the instructions printed to your terminal about modifying your
Next, run the generated database migrations:
Now restart the Phoenix server and re-navigate to
localhost:4000/todo_items and you should see the listing page for your TodoItems. Great!
Navigating the Generated Code
Now that we have the Todo app up-and-running, let’s navigate through the code to get a glimpse at how things work under the hood.
First, let’s take a look at index.ex, the generated Elixir code for the index LiveView. We notice five functions:
mount is called when the client connects and is used to set up the initial
socket. You will notice that there is no
render function, and that is because Phoenix uses a particular convention to display its templates: if there is an associated
index.html.heex adjacent to
index.ex, that template will be used.
handle_params is called whenever we have a live navigation event. These events are what you would normally have separate HTTP requests for. You can learn more about
handle_event is called whenever we have a JS “delete” event pushed to the page. Finally,
list_todo_items simply calls the associated context’s function.
Join me next time when we dive into
index.html.heex. In the mean time, feel free to browse through the additional generated code.
If you gained value from this post, feel free to throw me a dollar or two on my Buy Me a Coffee page, which you can find here:
Your support goes to the cost of keeping the server up and is never unappreciated. Thanks!
2 responses to “A Brief Introduction to Phoenix and LiveView (Part 1)”
[…] This is a continuation of Part 1, which you can find here:https://danieljaouendevelopment.com/2022/12/18/a-brief-introduction-to-phoenix-and-liveview-part-1/ […]
Thx for useful and fresh explanation! =)