How to use the assign function outside of a LiveView

  • Phoenix
  • Elixir


I have been looking into Elixir and Phoenix lately, and I'm following a pretty great course from The Pragmatic Studio

One of the exercises involves refactoring some code to extract reusable functionality outside of a LiveView.

In a LiveView it's very common to assign values to the socket. Here's an example lifted from the official documentation

def handle_event("inc_temperature", _value, socket) do
  {:ok, new_temp} = Thermostat.inc_temperature(
  {:noreply, assign(socket, :temperature, new_temp)}

However, I'm very inexperienced with both Elixir and Phoenix, and I couldn't figure out how to use the assign function from another module.

I searched the Phoenix documentation and I attempted to import Phoenix.Socket.assign, but the compiler would throw many errors.

What I actually needed is Phoenix.Component.assign which is documented in the Phoenix LiveView documentation instead.

Search engines and ChatGPT weren't helpful. So here it is.