You don’t need hooks for this. Here’s my approach:
phx-update
can take 4 possible values:
replace - the default operation. Replaces the element with the contents
ignore - ignores updates to the DOM regardless of new content changes
append - append the new DOM contents instead of replacing
prepend - prepend the new DOM contents instead of replacing
I created a new assign :update_action
and I’m passing it like this to the template: phx-update="<%= @update_action %>"
So, you only need to switch between append
or replace
in the :update_action
assign depending on your logic.
However, when filter form is changed, I want the collection items to be replaced instead of appended. When, for example, the sorting is changed, the collection of items should start from page 1.
Here, you would change :update_action
to replace
.
When you only load more without actually changing any filters, it would be in append
state.
So, in initial mount
, it’s set to append
Then, in handle_params
it’s set to replace
since this is where the logic happens when filtering
Then, in handle_event("load-more", _, _)
, I set it again to append
Hope this helps.