UndefinedFunctionError at GET / function nil.id/0 is undefined

I am integrating phx.gen.auth with the phoenix context guides . But some problem with fetch_current_cart plug in the router. I get this error in the index page.

But when i comment out the fetch_current_cart plug everything works fine.

UndefinedFunctionError <small>at GET</small> <small>/</small>

function nil.id/0 is undefined

Here is the code

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, {ShopWeb.LayoutView, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug :fetch_current_user
    plug :fetch_current_cart
  end



  def fetch_current_cart(conn, _opts) do
   if cart = ShoppingCart.get_cart_by_user_id(conn.assigns.current_user.id) do
      assign(conn, :cart, cart)
  else
      {:ok, new_cart} = ShoppingCart.create_cart(conn.assigns.current_user.id)
      assign(conn, :cart, new_cart)
   end
 end

Can someone help.

Thanks

conn.assigns.current_user may be nil if no user is logged in. You cannot fetch the user.id if you don’t know the user.

2 Likes

Thanks for pointing out. Sometimes I doubt whether I have a brain or not. :laughing:

If someone commits the same silly mistake, This is how the fetch_current_user plug must be.

 def fetch_current_cart(conn, _opts) do
  if conn.assigns[:current_user] do
    cart = ShoppingCart.get_cart_by_user_id(conn.assigns.current_user.id)
    assign(conn, :cart, cart)
  else
    conn
  end
end