I’m experimenting and I’ve created a todo list app that renders a lists of todos.
The todos are stored using an Agent in lib/app/todos
This is the code for the Agent:
defmodule App.Todos do
use Agent
def start do
Agent.start(
fn ->
[
%{title: "some stuff-1"},
%{title: "some stuff-2"},
%{title: "some stuff-3"}
]
end,
name: __MODULE__
)
end
def get(name) do
__MODULE__
|> Agent.get(& &1)
|> Enum.filter(fn item -> item.name == name end)
end
def list_todos do
Agent.get(__MODULE__, fn state -> state end)
end
def put(data) do
Agent.update(__MODULE__, fn state ->
[data | state]
end)
end
end
Here is my controller code:
defmodule AppWeb.TodoController do
use AppWeb, :controller
alias App.Todos
def index(conn, _params) do
todos = Todos.list_todos()
render(conn, "index.html", todoItems: todos, stuff: "xyz", oink: "blah")
end
def create(conn, _params) do
Todos.put(%{title: conn.body_params["todo"]})
todos = Todos.list_todos()
IO.inspect(conn.body_params["todo"])
render(conn, "index.html", todoItems: todos)
end
end
When I post todos they render as expected with one small problem.
When I start the app I get an error that says:
exited in: GenServer.call(App.Todos, {:get, #Function<2.53747013/1 in App.Todos.list_todos/0>}, 5000) ** (EXIT) no process: the process is not alive or there’s no process currently associated with the given name, possibly because its application isn’t started
If I start the agent by typing App.Todos.start() in the code base (I’ve been typing it at the bottom of the agent file) it will work per the auto reload of the app.
Question:
Is there anywhere I can place App.Todos.start() so that it works on the initial start of the app server and I don’t need to “manually” type it out after I’ve already started the server?