coen.bakker

coen.bakker

I have story_cards that render a list of authors, among other things. Clicking an author should open a modal, via a function set_modal_data/1. This function needs the to be passed one author (not all authors).

Is there a way to pass the set_modal_click/1 function to the story_card function component call (e.g. <.story_card ... on_author_click={...}/>? Currently, I am using slots to be able assign the set_modal_click/1 to the phx-click that should open the modal.

# current solution
<.story_card
  :for={story <- @stories}
  story={story}
>
  <:author let={author}>
    <span
      class="pub-cover-author-tag"
      phx-click={set_modal_data(%{"id" => author.id, "modal" => "user"})}
    >
      <%= author.username %>
    </span>
  </:author>
</.story_card>
# hypothesized solution
<.story_card
  :for={story <- @stories}
  story={story}
  let={author}
  on_author_click={set_modal_data(%{"id" => author.id, "modal" => "user"})}
/>

Ty

Showing Posts 1 to 10

ken-kost

ken-kost

I know you’re not using Surface but perhaps this documentation could help you.

if you have current_user stored in your socket, you could send it together with author

<.story_card
  :for={story <- @stories}
  story={story}
  current_user={@current_user}
  author={story.author}
</.story_card>

Something like that perhaps, then you could check inside story card if the current user is the author or not and act accordingly.

Not sure if I’m being relevant. :sweat_smile:

coen.bakker

coen.bakker OP

Rereading my post, I notice I should have explained it better. :sweat_smile:

There is a comprehension for authors inside the story_card function component: for author <- @authors do .... One story_card shows a html-element with a phx-click for each author.

<.story_card
  :for={story <- @stories}
  story={story}
>
  <:author let={author}>         <-- author comes from comprehension
    <span
      class="pub-cover-author-tag"
      phx-click={set_modal_data(%{"id" => author.id, "modal" => "user"})}
    >
      <%= author.username %>
    </span>
  </:author>
</.story_card>

So the comprehension giving the author map can be found here (made some adjustments for this post so might contain typo’s):

  attr :story, :map
  attr :on_title_click, JS, default: %JS{}
  slot :author
  def story_card(assigns) do
    ~H"""
    <div>
      <div>
        <.link phx-click={@on_title_click}>
          <%= @story.title %>
        </.link>
        <div class="pub-cover-authors">
          <%= for author <- @authors do %>
            <%= render_slot(@author, author) %>
          <% end %>
        </div>
      </div>
    </div>
    """
  end
sodapopcan

sodapopcan

You should be able to pass it as a capture:

<.story_card
  :for={story <- @stories}
  story={story}
  on_author_click={&set_modal_data/1}
/>

and then:

  phx-click={on_author_click.(%{"id" => author.id, "modal" => "user"})

I may also be misunderstand what you’re after, though!

coen.bakker

coen.bakker OP

Oh yes. I see what you mean. I haven’t thought of it that way yet.

The reason for my post was that I like to be able to see all my LiveView event calls from my LiveView modules.

So I try to prevent this:

defmodule AppWeb.PageLive do

  ...

  def render(assigns) do
    ~H"""
    <.some_component/>    <-- this component calls \"some_event\" from inside itself
    """
  end

  def handle_event("some_event", _, socket) do
    ...
    {:noreply, socket}
  end
end

Instead, I have been doing:

defmodule AppWeb.PageLive do

  ...

  def render(assigns) do
    ~H"""
    <.some_component on_some_click={JS.push("some_event", value: ...)}/> 
    """
  end

  def handle_event("some_event", _, socket) do
    ...
    {:noreply, socket}
  end
end

However, some components have bindings (e.g. phx-click) inside them that are inside a comprehension expression. For example:

  def some_component(assigns) do
    ~H"""
    <div>
      <%= for item <- @items do %>
        <span phx-click={JS.push("some_event", value: %{item: item})}/>
      <% end %>
    </div>
    """
  end

I was wondering if I can pass that JS.push("some_event", value: %{item: item}) from the last example/code block to the <.some_component/> component from the render function of the LiveView module, somehow.

Some like:

<.some_component
  let={item}
  on_some_click={JS.push("some_event", %{item: item})}
/>
sodapopcan

sodapopcan

That makes sense!

It should work with the capture:

def story_card(assigns) do
  ~H"""
  ...
    <li :for={author <- @authors}>
      <a phx-click={@on_author_click.(author)}>...</a>
    </li>
  ...
  """  
end
def render(assigns) do
  ~H"""
  <.story_card
    authors={@authors}
    on_author_click={&JS.push("some_event", value: %{author: &1})}
  />
  """
end

(sorry I forgot the @ in my original example)

Possibly you already got that but I wasn’t sure from your response :sweat_smile:

coen.bakker

coen.bakker OP

Great. Love it. :smiley:

Ty

coen.bakker

coen.bakker OP

Just got back to my computer to implement it and I am getting an error saying:

protocol Jason.Encoder not implemented for #App.Accounts.User<__meta__: #Ecto.Schema.Metadata<:loaded, "users">, ...> of type App.Accounts.User (a struct), Jason.Encoder protocol must always be explicitly implemented.
If you own the struct, you can derive the implementation specifying which fields should be encoded to JSON:

    @derive {Jason.Encoder, only: [....]}
    defstruct ...

It is also possible to encode all fields, although this should be used carefully to avoid accidentally leaking private information when new fields are added:

    @derive Jason.Encoder
    defstruct ...

Finally, if you don't own the struct you want to encode to JSON, you may use Protocol.derive/3 placed outside of any module:

    Protocol.derive(Jason.Encoder, NameOfTheStruct, only: [...])
    Protocol.derive(Jason.Encoder, NameOfTheStruct)
. This protocol is implemented for the following type(s): Any, Atom, BitString, Date, DateTime, Decimal, Ecto.Association.NotLoaded, Ecto.Schema.Metadata, Float, Integer, Jason.Fragment, Jason.OrderedObject, List, Map, NaiveDateTime, Time

I am not familiar with having to explicitly implement Jason.Encoder protocol for a struct I own (in this case User, which corresponds with the author variable from earlier). Is this error to be expected when implementing the solution you suggested, that you know? This might be a good opportunity for me to learn more about implementing the Jason.Encoder protocol, in that case.

edit:

This is the stack trace I am getting:

(jason 1.4.0) lib/jason.ex:164: Jason.encode!/2
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/js.ex:127: Phoenix.HTML.Safe.Phoenix.LiveView.JS.to_iodata/1
        (phoenix_html 3.3.1) lib/phoenix_html.ex:265: Phoenix.HTML.build_attrs/1
        (phoenix_html 3.3.1) lib/phoenix_html.ex:218: Phoenix.HTML.attributes_escape/1
        (app 0.1.0) lib/app_web/components/base_components.ex:668: anonymous fn/3 in AppWeb.BaseComponents."authors_label_list (overridable 1)"/1
        (elixir 1.14.0) lib/enum.ex:2468: Enum."-reduce/3-lists^foldl/2-0-"/3
        (app 0.1.0) lib/app_web/components/base_components.ex:667: anonymous fn/2 in AppWeb.BaseComponents."authors_label_list (overridable 1)"/1
        (app 0.1.0) /Users/.../app/lib/app_web/components/base_components.ex:586: AppWeb.BaseComponents.story_card/1
        (elixir 1.14.0) lib/enum.ex:2468: Enum."-reduce/3-lists^foldl/2-0-"/3
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/diff.ex:396: Phoenix.LiveView.Diff.traverse/7
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/diff.ex:571: anonymous fn/3 in Phoenix.LiveView.Diff.traverse_comprehension/5
        (elixir 1.14.0) lib/enum.ex:1780: Enum."-map_reduce/3-lists^mapfoldl/2-0-"/3
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/diff.ex:492: Phoenix.LiveView.Diff.traverse/7
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/diff.ex:544: anonymous fn/4 in Phoenix.LiveView.Diff.traverse_dynamic/7
        (elixir 1.14.0) lib/enum.ex:2468: Enum."-reduce/3-lists^foldl/2-0-"/3
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/diff.ex:396: Phoenix.LiveView.Diff.traverse/7
        (phoenix_live_view 0.18.17) lib/phoenix_live_view/diff.ex:544: anonymous fn/4 in Phoenix.LiveView.Diff.traverse_dynamic/7
        (elixir 1.14.0) lib/enum.ex:2468: Enum."-reduce/3-lists^foldl/2-0-"/3
sodapopcan

sodapopcan

Oh right, I was sort of afraid of that, lol. It’s just saying you can’t encode an Elixir struct into HTML which makes sense. I think you can just put @derive Json.Encoder in your schema. The idea is that it’s telling it how to convert a schema into JSON. That should work (I’m not actually trying these things as I type them). You could also explicitly pass the artist attributes as in your original example:

  phx-click={&JS.push("some_event", value: %{id: &1.id, name: &1.name, ...etc})}
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Be very careful with this. The user struct in this case is being sent to the JS front end unencrypted. I would strongly suggest pulling out specific keys that are relevant to the JS.

sodapopcan

sodapopcan

Right, you’d need to make sure you have the redacted fields set. Thanks for chiming in, I did not think of that!

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews