Search code examples
elixirphoenix-frameworkphoenix-live-view

Visibility and lifecycle of an anonymous function


I try to filterout removed items:

  defp react_to_event({:delete, item}, socket) do
    id = item.id

    filter_by_id = fn list ->
      Enum.filter(list, fn
        {:id, ^id} -> false
        _ -> true
      end)
    end

    {
      :noreply,
      socket
      |> update(:new_items, &filter_by_id/1)
      |> update(:items, &filter_by_id/1)
    }
  end

But it seems like a lifecycle or scoping is off here: i get unused variable filter_by_id and undefined function filter_by_id errors here. What's wrong with the code?


Solution

  • &filter_by_id/1 will look for a named filter_by_id/1 function in your module (or imported modules), not the anonymous function contained in the filter_by_id variable.

    The following should work:

    {
      :noreply,
      socket
      |> update(:new_items, filter_by_id)
      |> update(:items, filter_by_id)
    }
    

    & is used to captured named functions as variables and pass them as function arguments, but anonymous functions do not need to be captured because they can already be assigned in the first place.