How do Phoenix templates manage state?

Frederick John Source

I'm working on a card game in Elixir where the state of the game is managed by a GenServer. When the user navigates to "games/new" I've added a line in the GameController#new action to start the GenServer and return the initialized state. Then I can pass this state into the template by the call to render.

def new(conn, _params) do
    changeset =
      conn.assigns[:current_user]
      |> Ecto.build_assoc(:games)
      |> GamePlay.change_game()

      War.GamePlay.Game.start_game()

      %War.GamePlay.Game{user_cards: user_hand, computer_cards: comp_hand, status: status} =
        Server.read(War.GamePlay.Server)
    render(conn, "new.html", changeset: changeset, user_hand: user_hand, comp_hand: comp_hand, status: status)
  end

In my template, I can use these variables to grab the state like so,

<h4>  Game Status:  <%= @status %> </h4>

and it will return "in progress".

I don't want the user to navigate away from the page but how would I call my GenServer from the view? For example, in the game of war, the user will need to click "next card", how is this tied to the GenServer so that the button calls that function? How do I pass the current state to the template?

model-view-controllerelixirphoenix-framework

Answers

answered 8 months ago Justin Wood #1

Once the view has been rendered, you can no longer just call your GenServer. In this case, you will probably want to look into using channels. This would allow you to continue calling your GenServer upon some action that happens on the client.

comments powered by Disqus