Mastering Phoenix Framework – Part 3

Hi folks,

I hope you are doing well. In this blog, we will look at some essential concepts of the Phoenix app.

Live View

To create a live view we need to enter the following command.

mix phx.gen.live Accounts User users name:string age:…


This content originally appeared on DEV Community and was authored by Rushikesh Pandit

Hi folks,

I hope you are doing well. In this blog, we will look at some essential concepts of the Phoenix app.

Live View

To create a live view we need to enter the following command.

mix phx.gen.live Accounts User users name:string age:integer

The first argument is the context module, which serves as an API boundary for related resources. If the context already exists, it will be augmented with functions for the new resource.

The second argument is the schema module, which maps database fields to an Elixir struct.

The remaining arguments are the schema module's plural name (used as the table name) and an optional list of attributes with their names and types.

Check out the sample code for live view.

lib/my_app_web/live/my_live_view.ex

defmodule MyAppWeb.MyLiveView do
  use MyAppWeb, :live_view

  def render(assigns) do
    ~H"""
    <div>
      Hi from Live View.
    </div>
    """
  end

Now our live view is ready, so we need to add it to our router to use it. To do this, add the following code to your router.ex

scope "/", MyAppWeb do
    pipe_through :browser

    live "/", MyLiveView
end

Now, visit http://localhost:4000/ to see the live view in action.

Live Component

To create a live component we need to create a new file named my_component.ex in the following directory.

lib/my_app_web/live/my_component.ex

Add the following content in the above file.

defmodule MyAppWeb.MyComponent do
  use MyAppWeb, :live_component

  def render(assigns) do
    ~H"""
    <div>
      <h1><%= @title %></h1>
      <p><%= @description %></p>
    </div>
    """
  end
end

So, this component expects 2 values such as title and description. We need to pass these 2 values whenever we want to consume this component in our live view. To do this, we need to update our live view as follows.

lib/my_app_web/live/my_live_view.ex

defmodule MyAppWeb.MyLiveView do
  use MyAppWeb, :live_view
  alias MyAppWeb.MyComponent

  def render(assigns) do
    ~H"""
    <div>
      <.live_component module={MyComponent}
        id= "my-component"
        title={@title}
        description={@description}
      />
    </div>
    """
  end

  def mount(_params, _session, socket) do
    {:ok, assign(socket, title: "Hello, World!", description: "This is a description.")}
  end
end

In this example:

  • The live_component function is used to render MyAppWeb.MyComponent.
  • The module attribute is used to specify the component module.
  • The id is required and must be unique for each instance of the component.
  • title and description are passed as assigns to the component using {} syntax.

Access the Data in the Component:

Inside our live component's render function, we can access the passed data using @title and @description assigns.

Navigation

There are 2 types of navigation we are using in the Phoenix Framework.

  1. Server-side navigation
  2. Client-side navigation

Let's take a look at them one by one.

1. Server-side navigation

- redirect/2

Sends redirect response to the given URL. For security, :to only accept paths. Use the :external option to redirect to any URL. The response will be sent with the status code defined within the connection, via Plug.Conn.put_status/2. If no status code is set, a 302 response is sent.

Example

redirect(conn, to: "/login")

redirect(conn, external: "https://elixir-lang.org")

- push_navigate/2

The current LiveView will be shut down and a new one will be mounted in its place, without reloading the whole page. This can also be used to remount the same LiveView, in case you want to start fresh.

Option

:to - the required path to link to. It must always be a local path
:replace - the flag to replace the current history or push a new state. Defaults false.

Example

{:noreply, push_navigate(socket, to: "/")}
{:noreply, push_navigate(socket, to: "/", replace: true)}

- push_patch/2

When navigating to the current LiveView, handle_params/3 is immediately invoked to handle the change of params and URL state. Then the new state is pushed to the client, without reloading the whole page while also maintaining the current scroll position.

Option

:to - the required path to link to. It must always be a local path
:replace - the flag to replace the current history or push a new state. Defaults false.

Example

{:noreply, push_patch(socket, to: "/")}
{:noreply, push_patch(socket, to: "/", replace: true)}

2. Client-side navigation

- link/1

Generates a link to a given route. To navigate across pages, using traditional browser navigation, use the href attribute. To patch the current LiveView or navigate across LiveViews, use the patch and navigate respectively.

Attributes
navigate (:string) - Navigates from a LiveView to a new LiveView. The browser page is kept, but a new LiveView process is mounted and its content on the page is reloaded. It is only possible to navigate between LiveViews declared under the same router Phoenix.LiveView.Router.live_session/3. Otherwise, a full browser redirect is used.

patch (:string) - Patches the current LiveView. The handle_params callback of the current LiveView will be invoked and the minimum content will be sent over the wire, as any other LiveView diff.

href (:any) - Uses traditional browser navigation to the new location. This means the whole page is reloaded on the browser.

replace (:boolean) - When using :patch or :navigate, should the browser's history be replaced with pushState?

Defaults to false.

method (:string) - The HTTP method to use with the link. This is intended for usage outside of LiveView and therefore only works with the href={...} attribute. It has no effect on the patch and navigate instructions. In case the method does not work, the link is generated inside the form which sets the proper information. To submit the form, JavaScript must be enabled in the browser. Defaults to get.

csrf_token (:any) - A boolean or custom token to use for links with an HTTP method other than get. Defaults to true. Global attributes are accepted. Additional HTML attributes are added to the tag. Supports all globals plus: ["download", "hreflang", "referrerpolicy", "rel", "target", "type"].

Slots

inner_block (required) - The content rendered inside of the a tag.

Example

<.link href="/">Regular anchor link</.link>

<.link navigate={~p"/"} class="underline">home</.link>

<.link navigate={~p"/?sort=asc"} replace={false}>
  Sort By Price
</.link>

<.link patch={~p"/details"}>view details</.link>

<.link href={URI.parse("https://elixir-lang.org")}>hello</.link>

<.link href="/the_world" method="delete" data-confirm="Really?">delete</.link>

That's it for the day. In the next part, we will go through some more concepts of the Phoenix framework.

Feel free to reach out if you need help.

LinkedIn: https://www.linkedin.com/in/rushikesh-pandit-646834100/
GitHub: https://github.com/rushikeshpandit
Portfolio: https://www.rushikeshpandit.in

#myelixirstatus , #liveviewnative , #dockyard , #elixir , #phoenixframework


This content originally appeared on DEV Community and was authored by Rushikesh Pandit


Print Share Comment Cite Upload Translate Updates
APA

Rushikesh Pandit | Sciencx (2024-08-19T14:17:55+00:00) Mastering Phoenix Framework – Part 3. Retrieved from https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/

MLA
" » Mastering Phoenix Framework – Part 3." Rushikesh Pandit | Sciencx - Monday August 19, 2024, https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/
HARVARD
Rushikesh Pandit | Sciencx Monday August 19, 2024 » Mastering Phoenix Framework – Part 3., viewed ,<https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/>
VANCOUVER
Rushikesh Pandit | Sciencx - » Mastering Phoenix Framework – Part 3. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/
CHICAGO
" » Mastering Phoenix Framework – Part 3." Rushikesh Pandit | Sciencx - Accessed . https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/
IEEE
" » Mastering Phoenix Framework – Part 3." Rushikesh Pandit | Sciencx [Online]. Available: https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/. [Accessed: ]
rf:citation
» Mastering Phoenix Framework – Part 3 | Rushikesh Pandit | Sciencx | https://www.scien.cx/2024/08/19/mastering-phoenix-framework-part-3/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.