Why Wont my GET request go through?

I’m trying to make a simple dictionary app and I can’t get the httpoison get request to go through with the word the user types in the input. Here’s my code:

defmodule LightAppWeb.DictionaryPage do
  use LightAppWeb, :live_view
  import HTTPoison

  def mount(_params, _session, dictionaryStates) do
    {:ok, assign(dictionaryStates, word: "")}
  end

  def make_request(url) do
    IO.puts("Request URL: #{url}")

    case HTTPoison.get(url) do
      {:ok, %{status_code: 200, body: body}} ->
        # Handle the successful response
        IO.inspect(body)

      {:ok, %{status_code: status_code}} ->
        # Handle other successful status codes if needed
        IO.puts("Received status code: #{status_code}")

      {:error, error} ->
        # Handle the request error
        IO.puts("Request error: #{inspect(error)}")
    end
  end

  def render(assigns) do
    ~H"""
    <p>What word do you want to learn more about?</p>
    <input class="border border-2 border-[#000000]" value={@word} />
    <button phx-click="request">Submit</button>
    """
  end

  def handle_event("request", %{"value" => word}, dictionaryStates) do
    url = "https://api.dictionaryapi.dev/api/v2/entries/en/#{word}"
    make_request(url)
    {:noreply, dictionaryStates}
  end
end

For example, if the user types “hello” in the input, site would hit the endpoint https://api.dictionaryapi.dev/api/v2/entries/en/ instead of https://api.dictionaryapi.dev/api/v2/entries/en/hello

Short answer: because you are not sending a word.

Why? Because phx-click sends phx-value-x’s values declarated in the same element, like this:

<button phx-click="request" phx-value-word={@word}>Submit</button>

and then handle the event

def handle_event("request", %{"word" => word}, status) do

For this to work thou, you’d need to keep in socket assigns the variable word and update it on input change. In that scenario sending the variable isn’t necessary at all since it’s already available in socket assigns in handle_event’s scope.

What you want is to create a form. Check out the first couple of paragraphs of the docs below, and you’ll be up in no time. Following that guide you’ll notice it’s not necessary to keep track of word at all.

https://hexdocs.pm/phoenix_live_view/form-bindings.html

PS: Friendly Clean Code advice: call it socket, not dictionaryStates.

PS2: Re reading your title, I believe you are under the impresion that click goes through HTTP GET, but in fact is a socket call. Pro tip: to debug LiveView apps, you can see what is being sent using dev tools

3 Likes