Search⌘ K
AI Features

Keeping State With Elixir Agents

Explore how to maintain and update state in Elixir applications using the Agent module. Understand how this state management supports building an HTML domain-specific language with macros that generate dynamic and nested HTML efficiently. Gain hands-on experience with the Agent API and macro integration to create a minimal yet functional HTML generator.

The Elixir Agent module provides a simple way to store and retrieve the state in our application. Let’s see how easy it is to manage the state with an Agent process, by executing the following commands in sequence in the iex shell:

iex> {:ok, buffer} = Agent.start_link fn -> [] end 
# Output: {:ok, #PID<0.130.0>}
iex> Agent.get(buffer, fn state -> state end) 
# Output: []
iex> Agent.update(buffer, &["<h2>Hello</h2>" | &1]) 
# Output: :ok
iex> Agent.get(buffer, &(&1)) 
# Output: ["<h2>Hello</h2>"]
iex> for i <- 1..3, do: Agent.update(buffer, &["<td><#{i}</td>" | &1]) 
# Output: [:ok, :ok, :ok]
iex> Agent.get(buffer, &(&1))
# Output: ["<td><3</td>", "<td><2</td>", "<td><1</td>", "<h2>Hello</h2>"]
Terminal 1
Terminal
Loading...

The use of Agent module:

The Agent module has a small API, which focuses on providing quick access to the state. In the example given above, we started an Agent with an initial state of []. Next, we ...