|
1 | 1 | defmodule RedditWeb.SubscriptionsLive do |
2 | 2 | use RedditWeb, :live_view |
3 | 3 |
|
4 | | - def mount(_params, %{"current_user" => user_id}, socket) do |
5 | | - socket = |
| 4 | + alias Reddit.Community.Subscription |
| 5 | + alias Reddit.Repo |
| 6 | + |
| 7 | + import Ecto.Query, only: [where: 2] |
| 8 | + |
| 9 | + def mount(_params, %{"current_user" => u_id, "community" => c_id}, socket) do |
| 10 | + if Subscription |> where(user_id: ^u_id) |> where(community_id: ^c_id) |> Repo.all() !== [] do |
| 11 | + socket = |
| 12 | + assign(socket, |
| 13 | + user: u_id, |
| 14 | + community: c_id, |
| 15 | + status: "Leave Community", |
| 16 | + btn_status: "secondary", |
| 17 | + disable_with: "Leaving...") |
| 18 | + |
| 19 | + {:ok , socket} |
| 20 | + else |
| 21 | + socket = |
6 | 22 | assign(socket, |
7 | | - user: user_id, |
| 23 | + user: u_id, |
| 24 | + community: c_id, |
8 | 25 | status: "Join Community", |
9 | 26 | btn_status: "success", |
10 | 27 | disable_with: "Joining...") |
11 | 28 |
|
12 | | - {:ok , socket} |
| 29 | + {:ok , socket} |
| 30 | + end |
13 | 31 | end |
14 | 32 |
|
15 | 33 | def render(assigns) do |
16 | 34 | ~L""" |
17 | | - <button class="btn btn-<%= @btn_status %> text-uppercase float-right" phx-click="toggle-status" |
18 | | - phx-disable-with=<%= @disable_with %>> |
| 35 | + <button class="btn btn-<%= @btn_status %> text-uppercase float-right" |
| 36 | + phx-value-user="<%= @user %>" |
| 37 | + phx-value-community="<%= @community %>" |
| 38 | + phx-click="toggle-status" |
| 39 | + phx-disable-with=<%= @disable_with %>> |
19 | 40 | <%= @status %> |
20 | 41 | </button> |
21 | 42 | """ |
22 | 43 | end |
23 | 44 |
|
24 | | - def handle_event("toggle-status", _, socket) do |
25 | | - socket = |
| 45 | + def handle_event("toggle-status", %{"user" => u_id, "community" => c_id}, socket) do |
| 46 | + if Subscription |> where(user_id: ^u_id) |> where(community_id: ^c_id) |> Repo.all() !== [] do |
| 47 | + Subscription.delete_old_relationship(u_id, c_id) |
| 48 | + |
| 49 | + socket = |
| 50 | + assign(socket, |
| 51 | + user: u_id, |
| 52 | + community: c_id, |
| 53 | + status: "Join Community", |
| 54 | + btn_status: "success", |
| 55 | + disable_with: "Joining...") |
| 56 | + |
| 57 | + :timer.sleep(500) |
| 58 | + |
| 59 | + {:noreply , socket} |
| 60 | + else |
| 61 | + Subscription.build_relationship(u_id, c_id) |
| 62 | + |
| 63 | + socket = |
26 | 64 | assign(socket, |
| 65 | + user: u_id, |
| 66 | + community: c_id, |
27 | 67 | status: "Leave Community", |
28 | 68 | btn_status: "secondary", |
29 | 69 | disable_with: "Leaving...") |
30 | 70 |
|
31 | | - :timer.sleep(500) |
| 71 | + :timer.sleep(500) |
32 | 72 |
|
33 | | - {:noreply, socket} |
| 73 | + {:noreply , socket} |
| 74 | + end |
34 | 75 | end |
35 | 76 | end |
0 commit comments