Hello,
I'm new to Elixir and Phoenix and found myself repeating code in the same function.
def handle_event("submit_ai_search", %{"card" => params}, socket) do
send(self(), {:loading, true})
changeset = %Cards.Card{}
|> Cards.Card.validate_search_term(params)
|> Map.put(:action, :insert)
if changeset.valid? do
response = AiSearch.search("-", params["search_term"])
case AiSearch.handle_response(response) do
{:ok, result} ->
send(self(), {:search_results, result})
{:noreply, assign(socket, :changeset, changeset)}
{:error, message} ->
changeset = changeset
|> Ecto.Changeset.add_error(:search_term, message)
send(self(), {:loading, false})
{:noreply, assign(socket, :changeset, changeset)}
end
else
send(self(), {:loading, false})
{:noreply, assign(socket, :changeset, changeset)}
end
end
end
This line {:noreply, assign(socket, :changeset, changeset)} is repeated 3 times and the send(self(), {:loading, false}) is repeated twice.
Is there a better way to write these blocks of code to avoid code duplication? It would really help if someone could point me in the right direction.
Thanks 🙂