Skip to content

Commit f4344b4

Browse files
authored
Add using generic map manipulation on assigns variable to common pitfalls (#4041)
1 parent f5ee3f8 commit f4344b4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

guides/server/assigns-eex.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,36 @@ is passed to each child component, only re-rendering what is necessary.
238238
However, generally speaking, it is best to avoid passing `assigns` altogether
239239
and instead let LiveView figure out the best way to track changes.
240240

241+
### Modifying the `assigns` variable
242+
243+
Never modify the `assigns` variable in a function component through generic functions like `Map.put/3` or `Map.merge/2`. Instead, use `Phoenix.Component.assign/2`, `Phoenix.Component.assign/3`, `Phoenix.Component.assign_new/3`, or `Phoenix.Component.update/3`. If you modify the `assigns` variable with e.g. `Map.put/3`, those assigns inside your `HEEx` template will not update after the initial render. Using the LiveView specific assign functions is required for change tracking to work.
244+
245+
So, **never do this**:
246+
247+
```elixir
248+
def card(assigns) do
249+
assigns = Map.put(assigns, :sum, Enum.sum(assigns.values))
250+
251+
~H"""
252+
<p>{@sum}</p>
253+
"""
254+
end
255+
```
256+
257+
But instead do this:
258+
259+
```elixir
260+
def card(assigns) do
261+
assigns = assign(assigns, :sum, Enum.sum(assigns.values))
262+
263+
~H"""
264+
<p>{@sum}</p>
265+
"""
266+
end
267+
```
268+
269+
If you use `Map.put/3` instead of `assign/3` here, the `sum` assign will not update if you change the `values` after the initial render of the `HEEx` template.
270+
241271
### Comprehensions
242272

243273
HEEx supports comprehensions in templates, which is a way to traverse lists
@@ -288,3 +318,5 @@ To sum up:
288318
1. Avoid defining local variables inside HEEx templates, except within Elixir's constructs
289319

290320
2. Avoid passing or accessing the `assigns` variable inside HEEx templates
321+
322+
3. Only use LiveView specific assign functions to modify the `assigns` variable

0 commit comments

Comments
 (0)