elixirphoenix-frameworkphoenix-live-view

How to update an element on a Live page once a background task has been finished?


I have a table on a LV page. Each row has a button which is supposed to refresh data in a row. To refresh it, it has to send at least one request to an external API which may take a few seconds or as well as a few minutes. Data received from an external API gets saved into a DB.

I could make a user wait, but it'll be better to create a background task and return a response immediately which says something like "being updated"

Once a response has been received, how will I notify a live page about this, to then make it refresh its data?


Solution

  • let's say you handled the click event, triggered a background job, and updated the state of the socket with a kind of "updating..." message.

    now the background job finished successfully and should notify the original liveview process. it needs to send a message to this liveview. Phoenix.PubSub well be used for this at best.

    the liveview should subscribe to a topic, typically inside mount(), the background job will be the publisher, it will broadcast a message -typically a tuple holding the updated record after being fetched- to all subscribers, the liveview process is internally a gen_server where a handle_info callback can be implemented, in your handle_info/2 you can pattern match on that message and update you socket state accordingly.