Phoenix/LiveView: key :items_per_page not found in: #Phoenix.LiveView.Socket.AssignsNotInSocket<>

Hello everyone,

I’m building a pagination component that should calculate the pages based on the amount of results I got from the database. The shortened template code is the following:

<div>
  <span class="mx-2">Seite <%= @current_page %> von <%= calculate_max_pages(@socket, @result_amount) %></span>
</div>

My component looks like this:

defmodule ExampleWeb.PaginationComponent do
  use ExampleWeb, :live_component

  def mount(socket) do
    {:ok,
     assign(socket,
       current_page: 1,
       items_per_page: 15
     )}
  end

  def calculate_max_pages(socket, result_amount) do
    max_pages = Float.ceil(result_amount / socket.assigns.items_per_page)

    if max_pages < 1 do
      1
    else
      max_pages
    end
  end
end

I guess that the error occurs because I invoke a socket in the template but I don’t know how I can otherwise access the items_per_page variable that I declared in the mount method.

Also: I’m new to Elixir and functional programming. I’m sure there is a way to get ride of the if else and write something more ,functional" but I’m not sure how. Pattern matching is often used but I don’t see a solution for my case.

I really appreciate your help.

Hello everyone,

I came up with a solution and I understand my initial problem now…

My solution now looks like this:

def update(assigns, socket) do
    socket =
      assign(socket,
        max_pages: calculate_max_pages(assigns.result_amount, 15)
      )

    {:ok, socket}
  end

I just update the max pages and it’s working now :slight_smile: but maybe there is a smarter way.