waseigo
How to JS.push and trigger a handled event on all items of @streams.something in a LiveView?
I have a LiveView that contains a text input field with phx-change tied to an event called “search” that searches locations in the database for the string in the text input field, and displays the results of @streams.locations using the table core component.
Each location item on the table has a “keep” action that gets triggered with JS.push, which adds the item to a “kept” list of locations in assigns. This way the user adds items from the search results’ stream (@streams.locations) to a list, before committing this “kept” list to the database with another button.
How do I implement an action that applies the “keep” action on the entire @streams.locations, i.e. a “keep all” action?
I tried a button with phx-click={JS.push("keep_all")} and then accessing socket.assigns.streams.locations within handle_event("keep_all", _params, socket), but IIUC the LiveView has no knowledge of what’s shown in the browser, as the stream items are not in memory.
I then tried something like this:
JS.push("keep_all", value: %{locations: Enum.with_index(@streams.locations)})
and got:
** (ArgumentError) streams can only be consumed directly by a for comprehension.
If you are attempting to consume the stream ahead of time, such as with
`Enum.with_index(@streams.locations)`, you need to place the relevant information
within the stream items instead.
In other words: what is the idiomatic way of using JS.push to trigger an event that does something across all items in streams.something?
Most Liked
jswanner
A simple approach would be to have a separate assign with all the IDs, and when someone clicks “keep all” use that all IDs assign
cmo
I’m not sure if you can. My first instinct would be to write a hook that queries those rows and sends a list of IDs to the backend.
Last Post!
KP123
I would apply a data-location-id attribute to each element in the list. Then I’d add a SelectionList hook to the list itself. The hook can listen for a keep-all event, iterate over all its children to build a list of IDs, then push the result to the server.
Edit: @cmo already suggested this
Popular in Questions
Other popular topics
Latest Phoenix Threads
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









