coen.bakker

coen.bakker

Send message, `send(pid, message)`, from controller to a LiveView process not possible? If so, why not?

I was trying out a pattern I haven’t tried before: sending a message from a regular API controller to a LiveView process.

See code below for some of the relevant code. In a nutshell. One route for LiveView showing a registration form. One route for handling POST requests from that form. On form submit an AJAX POST request is made from the LiveView. In case there are any validation errors the form controller tries to send a message to the LiveView. At this point that message is just a non-sense test message. The LiveView does not receive the message, however.

# Router
    live "/form", FormLive
    post "/form", FormController, :create

# PageLive
      <script>
        function handleSubmit(event) {
          event.preventDefault()
          const form = event.srcElement
          const formdata = new FormData(form)
          const ajax = new XMLHttpRequest()
          ajax.open("POST", "/form", true)
          const crsfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
          ajax.setRequestHeader('x-csrf-token', crsfToken)
          ajax.send(formdata)
        }
      </script>

      def handle_info(:hello, socket) do
        IO.puts "RECEIVED" # Does not print after controller has sent the message
        {:noreply, socket}
      end

# RouteController
        # one or several validation errors
        %{"sender_pid" => sender_pid} = changeset.params
        IO.inspect sender_pid # "#PID<0.2900.0>" Note: String
        pid = String.slice(sender_pid, 5..-2)
        pid = pid(pid) |> IO.inspect # #PID<0.2900.0>
        send(pid, :hello)
        conn
        |> Plug.Conn.resp(406, "Not all form requirements have been met.")
        |> Plug.Conn.send_resp()

I hope this code provides sufficient context for my question: It seems I can’t send messages from my controller to the LiveView, why is that? I reckon I can use PubSub to get the job done, but I prefer to understand why the pattern I’m trying doesn’t work. I looked around in docs etc., but haven’t found a definite answer, yet.

Marked As Solved

derek-zhou

derek-zhou

You can send message from anywhere to anywhere. Most likely you didn’t have the right pid. No one knows the pid except the LV process itself and its supervisor. How did you get the info to the controller?

Also Liked

LostKobrakai

LostKobrakai

I’d suggest taking a look at trigger-action. It allows LV form handling to trigger a POST request once the form is validated, up until that everything is handled as normal using just the LV.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

As a design question, can you elaborate on why you’re doing it this way instead of submitting the form into the live view process itself? This seems like a much more complicated way of achieving phx-submit.

axelson

axelson

Scenic Core Team

FYI mix phx.gen.auth —live was announced at ElixirConf this year. I’m not sure if the code for it is available yet but that may provide some patterns that you can use here.

Last Post!

coen.bakker

coen.bakker

@benwilson512 @Nicd @axelson

Thank you for replies. I’m soaking in all the input. Appreciate all the lessons learnt during this project.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement