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

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews