In Node if I want the data from a JSON api I do:
const response = await fetch('https://api.whatever.com');
What is the live view version of the fetch line I posted above?
When I search for (and use LLM’s to give me examples of) equivalent code for Elixir Liveview the replies are always seem large and bulky.
Claude AI gave me all this stuff
# First, we need to set up our LiveView module
defmodule MyAppWeb.ApiDemoLive do
use MyAppWeb, :live_view
require Logger
def mount(_params, _session, socket) do
# Initial state
{:ok, assign(socket,
results: nil,
loading: false,
error: nil
)}
end
def render(assigns) do
~H"""
<div class="container mx-auto p-4">
<h1 class="text-2xl font-bold mb-4">API Data Demo</h1>
<button phx-click="fetch_data" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Fetch Data
</button>
<%= if @loading do %>
<div class="mt-4">Loading data...</div>
<% end %>
<%= if @error do %>
<div class="mt-4 text-red-500">Error: <%= @error %></div>
<% end %>
<%= if @results do %>
<div class="mt-4">
<h2 class="text-xl font-semibold mb-2">Results:</h2>
<pre class="bg-gray-100 p-4 rounded"><%= Jason.encode!(@results, pretty: true) %></pre>
</div>
<% end %>
</div>
"""
end
def handle_event("fetch_data", _, socket) do
# Set loading state
socket = assign(socket, loading: true, error: nil)
# Start async operation
%{pid: pid} = Task.async(fn -> fetch_api_data() end)
{:noreply, assign(socket, async_task: pid)}
end
# Handle successful API response
def handle_info({ref, result}, socket) when is_reference(ref) do
# Clean up the task
Process.demonitor(ref, [:flush])
case result do
{:ok, data} ->
{:noreply, assign(socket, results: data, loading: false)}
{:error, reason} ->
{:noreply, assign(socket, error: reason, loading: false)}
end
end
# Handle task failure
def handle_info({:DOWN, _ref, :process, _pid, reason}, socket) do
{:noreply, assign(socket, loading: false, error: "Process failed: #{inspect(reason)}")}
end
# Function to fetch data from API
defp fetch_api_data do
case HTTPoison.get("https://jsonplaceholder.typicode.com/posts/1") do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, Jason.decode!(body)}
{:ok, %HTTPoison.Response{status_code: status_code}} ->
{:error, "API returned status code: #{status_code}"}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, "HTTP client error: #{inspect(reason)}"}
end
end
end
# In your router.ex file:
# live "/api-demo", ApiDemoLive
# Make sure to include these dependencies in your mix.exs:
# {:httpoison, "~> 2.0"},
# {:jason, "~> 1.4"}