Trying to understand assigns vs socket.assigns

Hello everyone,

i’m trying to understand how assigns work, so considering the following

 def update(assigns, socket) do
    IO.inspect("assigns")
    IO.inspect(assigns)
    {:ok, socket |> assign(assigns)}
  end

what is the difference between assigns and socket.assigns

socket.assigns are the ones that have been assigned to the socket, either by you or the default update, which is assign(socket, assigns).

assigns are the incoming assigns, either from a parent liveview/component or send_update.

Also a tip, IO.inspect(assigns, label: «assigns») :slight_smile:

2 Likes

i’m sorry, but can you please give an example for this on how this works.

Also if a parent liveview component
has the following

    <.live_component module={PentoWeb.Components.BightnessLevel}
    id="brightness_comp" brightness="35"/>
    Local value = <%=@local_value %>
   <button phx-click="sendValue" phx-target={@myself}>
        Adjust brightness
    </button>

I have the brightnesslevel child component that is interested on the brightness value. now in the sendValue method in the parent component i’m doing the following (changing the brightness value)

{:noreply,
 socket
 |> assign(:brightness, "85")}

this change does not get reflected on the child component, based on the explanation given by you, i assume this is because we are just assigning to the socket value only and not sending the change to the child component ? so in order for the change to take effect i need to add the following line as well

send_update(PentoWeb.Components.BightnessLevel,
  id: "brightness_comp",
  brightness: "95"
)

and then it works, is this correct ? or is there a more simpler way of handling this

No, it is because you’ve hardcoded the brightness to 35.

Maybe you want something like this?

<.live_component 
  module={PentoWeb.Components.BightnessLevel}
  id="brightness_comp"
  brightness=<%= @brightness %>
/>

Also, you don’t need to set the target to @myself in the LiveView. Sending to the LiveView is default behaviour.