Skip to content

Instantly share code, notes, and snippets.

Avatar
🧭
Working on startupcompass.io

TS Lim tslim

🧭
Working on startupcompass.io
View GitHub Profile
View live_component_data.ex
# In LiveView
<%= live_component @socket, MyApp.UserLive.CustomComponent, id: "custom", foo: "foo", bar: "bar" %>
# In custom_component.ex
socket.assigns.foo # returns "foo"
socket.assigns.bar # returns "bar"
# In CustomComponent Template
<%= @foo %>
<%= @bar %>
View live_component_target.ex
# in live_component.html.leex
<%= f = form_for @changeset, "#",
id: "form",
phx_target: @myself, # Don't forget this
phx_change: "validate",
phx_submit: "save" %>
# Link to send delete event to the live component
<%= link "Delete User", to: "#", phx_click: "delete", phx_target: @myself, phx_disable_with: "Deleting..." %>
View live_modal.ex
# in router
scope "/", MyApp do
...
live "/users/new", UserLive.Index, :new
live "/users/:id/edit", UserLive.Index, :edit
...
end
# in live/user_live/index.html.leex
<%= if @live_action in [:new, :edit] do %>
View live_dashboard.ex
scope "/" do
pipe_through [:browser, :admin_access]
live_dashboard "/admin/dashboard",
metrics: MyApp.Telemetry,
env_keys: ["RENDER_GIT_COMMIT"] # Depends on your infra setup
end
View customise_templates.ex
# Set root layout in pipeline
defmodule MyApp.Router do
pipeline :browser do
...
plug :put_root_layout, {MyApp.LayoutView, :root}
...
# Set root layout in routes
scope "/", MyApp do
View page_title.ex
defp apply_action(socket, :index, _params) do
assign(socket, :page_title, "Your Page Title")
end
# OR
def handle_params(params, uri, socket) do
{:noreply,
socket
|> assign(:page_title, "You Page Title")
...
View uri.ex
def handle_params(params, uri, socket) do
{:noreply,
socket
|> assign(:uri, uri)
...
View actions.ex
def handle_params(params, uri, socket) do
{:noreply,
socket
|> assign(:page, params["page"] || socket.assigns.page)
|> assign(:order_by, params["order_by"] || socket.assigns.order_by)
|> apply_action(socket.assigns.live_action, params)
|> fetch_users()}
end
def handle_event("search", %{"keyword" => keyword}, socket) do
View pubsub.ex
def mount(_params, session, socket) do
{:ok,
socket
|> subscribe_to_pubsub()
...
end
def handle_info(_message, socket) do
{:noreply, fetch_users(socket)}
end
View fetch_resource.ex
def mount(_params, _session, socket) do
{:ok, fetch_users(socket)}
end
def handle_event("delete", %{"id" => id}, socket) do
user = Accounts.get_user!(id)
{:ok, _} = Accounts.delete_user(user)
{:noreply, fetch_users(socket)}
end