Instead of writing out the exact same code that I already have in one function is it not possible to just call the handle_event function inside another?
Hey @Daniel1 there are a few ways to deduplicate code. If you show what you have it’ll make it a bit simpler. At a high level though you have basically two options:
def handle_event(event, params, socket) when event in ["event1", "event"2] do
# common code
end
OR
def handle_event("event1", params, socket) do
# maybe do something with params or socket
handle_common_event(params, socket)
end
def handle_event("event2", params, socket) do
# maybe do something with params or socket
handle_common_event(params, socket)
end
thanks for your reply, I’m trying to add a reddit like upvoting system to my app, below is the code.
def handle_event("upvote", %{"num" => num, "ref" => ref}, %{assigns: %{qupvotes: true}} = socket) do
# would like to call the downvote handle_event here
{:noreply, assign(socket, qupvotes: false)}
end
def handle_event("upvote", %{"num" => num, "ref" => ref}, socket) do
IO.inspect(socket.assigns.qupvotes)
user_data = from q in Qna.Questions, where: q.id == ^ref
question = Repo.one(user_data)
changeset = Qna.Questions.update_changeset(question, %{upvotes: String.to_integer(num) + 1})
Repo.update(changeset)
questions = socket.assigns.questions
id = String.to_integer(ref)
num = 1
updated_questions =
questions
|> Enum.map(fn
question when question.id == id ->
question
|> Map.update!(:upvotes, &(&1 + num))
question ->
question
end)
new_qupvotes = !socket.assigns.qupvotes
new_socket = assign(socket, questions: updated_questions, qupvotes: new_qupvotes)
{:noreply, new_socket}
end
def handle_event("downvote", %{"num" => num, "ref" => ref}, socket) do
IO.inspect(socket.assigns.qupvotes)
user_data = from q in Qna.Questions, where: q.id == ^ref
question = Repo.one(user_data)
update_data = Qna.Questions.update_changeset(question, %{upvotes: String.to_integer(num) - 1})
Repo.update(update_data)
questions = socket.assigns.questions
id = String.to_integer(ref)
num = 1
updated_questions =
questions
|> Enum.map(fn
question when question.id == id ->
question
|> Map.update!(:upvotes, &(&1 - num))
question ->
question
end)
new_socket = assign(socket, questions: updated_questions)
{:noreply, new_socket}
end
Right so because one option is to simply:
def handle_event("upvote", params, %{assigns: %{qupvotes: true}} = socket) do
handle_event("downvote", params, assign(socket, qupvotes: false)
end
Another would be the function extraction option where you extract the contents of your "downvote"
clause into a handle_downvote
function and have both your handle_event
clauses call it.
1 Like
ah okay that makes sense, thank you for your help!