live_props v0.2.2 LiveProps.LiveView View Source

Use this module inside a Phoenix.LiveView to expose to add state to your LiveView.

LiveView Lifecycle with LiveProps

LiveProps injects lightweight Phoenix.LiveView.mount/3 and Phoenix.LiveView.handle_info/2 callbacks to help manage state.

If you define your own mount, it will be run after defaults states have been assigned but before computed states.

The reason we assign computed states last is because they may depend on data from params or session. LiveProps does not handle params and session so you will need to manually assign them in your own mount callback, if needed.


  defmodule ThermostatLive do
    # If you generated an app with mix --live,
    # the line below would be: use MyAppWeb, :live_view
    use Phoenix.LiveView
    use LiveProps.LiveView

    state :user_id, :integer
    state :scale, :atom, default: :fahrenheit
    state :temperature, :float, compute: :get_temperature

    def render(assigns) do
      Current temperature is <%= @temperature %>

    def mount(_, %{"current_user_id" => user_id}, socket) do
      # socket.assigns.scale already has a default value
      {:ok, assign(socket, :user_id, user_id)}

    def get_temperature(assigns) do
      Temperature.get_user_reading(assigns.user_id, assigns.scale)

First we defined a :user_id state. This doesn't really do anything other than serve as documentation, since we assign it manually in the mount callback. Still, depending on your preferences, you may find it helpful to have a list of all assigns in one place.

Next we defined the :scale state and gave it a default value. This value will be assigned automatically on mount and will be available in any custom mount you define.

Finally we defined the :temperature state, with the options compute: :get_temperature. This means this state will be calculated by the get_temperature/1 function, which takes the current assigns as an argument and returns the value to be assigned.