phoenix_live_view icon indicating copy to clipboard operation
phoenix_live_view copied to clipboard

Documenting the default assigns for socket

Open gworkman opened this issue 2 years ago • 3 comments

Environment

  • Elixir version (elixir -v): 1.13.4
  • Phoenix version (mix deps): 1.6.11
  • Phoenix LiveView version (mix deps): 0.17.11 (but looking at latest docs on hex.pm)
  • Operating system: MacOS
  • Browsers you attempted to reproduce this bug on (the more the merrier):
  • Does the problem persist after removing "assets/node_modules" and trying again? Yes/no:

About

I was recently following the LiveView uploads guide to add some uploads to my application. While implementing this feature, I changed the name of one of the assigns from :uploaded_files to :uploads, as below:

  def mount(_params, _session, socket) do
    {:ok,
     socket
     |> assign(:uploads, [])
     |> allow_upload(:csv, accept: [".csv"], max_entries: 1)}
  end

However, this led to an unexpected error:

** (exit) an exception was raised:
    ** (BadMapError) expected a map, got: []

After digging into it, I discovered that in the function uploaded_entries/2 there is the following case statement, which uses the default assign :uploads, which I had set to an empty list.

def uploaded_entries(%Socket{} = socket, name) do
    entries =
      case Map.fetch(socket.assigns[:uploads] || %{}, name) do
        {:ok, conf} -> conf.entries
        :error -> []
      end

    # ...

end

I noticed a little further down the live uploads guide that it states that Uploads are populated in an @uploads assign in the socket.. I was thinking it would be good to add a warning to the user that the :uploads assign is reserved for use further up in the guide? The simple solution is to add a callout in the docs that makes this pretty clear, but I think it might also be helpful to have the compiler warn the user if they use a default assign.

I don't know if there are other default assigns (or if they are documented somewhere), but a list of them might also be helpful for users

I'm happy to help contribute docs and code to this issue! 😄 Thanks!

Update: fix formatting

gworkman avatar Aug 28 '22 18:08 gworkman

Great report! We should probably start raising if someone explicitly assigns :uploads. This way we will avoid errors in the future. :)

josevalim avatar Aug 28 '22 18:08 josevalim

Thanks, @josevalim!

I would love to help with this issue if given a pointer in the right direction!

gworkman avatar Aug 29 '22 07:08 gworkman

I would love to help with this issue if given a pointer in the right direction!

Hey @gworkman assigns are validated in assign and assign_new functions, here's an example validating :flash: https://github.com/phoenixframework/phoenix_live_view/blob/78bbbbd30413d81440b91f1a619319339d22fd94/lib/phoenix_component.ex#L1264-L1268

You can do the same for :uploads

leandrocp avatar Oct 14 '22 17:10 leandrocp