webdeb
JSON with LiveView
Hi, we have an NextJS Frontend Application which is basically React.
Now we would like to use a Phoenix App as a Service for some Live data. But we only need the JSON no HTML. Is Phoenix LiveView a good fit for this, or should we go with the low-level Phoenix Channels.
In comparison, I think that Channels is really low-level. On the other hand LiveView is very high-level and too HTML specific. IMHO something like LiveState would be a cool thing.
For example const { state, dispatch } = useLiveState() (React hooks)
Most Liked Responses
methyl
Hey there.
I actually think it’s an idea with a lot of potential and use-cases that could be supported either in LiveView or as a separate library.
Being able to use whole React ecosystem while keeping the state in sync with your GenServers (or other abstraction) is something that we already experimented with. Take a look at this repo: GitHub - surferseo/livedata_todomvc · GitHub which is a proof of concept for the idea.
While the POC implementation is hideous, the API is really clean and powerful - check out livedata_todomvc/lib/phoenix_livedata_todomvc_web/live_data/todo_state.ex at master · surferseo/livedata_todomvc · GitHub and livedata_todomvc/assets/js/containers/TodoList.js at master · surferseo/livedata_todomvc · GitHub.
If you are interested in hearing more, check out this video https://www.youtube.com/watch?v=fvNy9bh8_vs where I talk a bit about motivations and the ugly internals.
Trying to make it play well with LiveView makes a lot of sense, as it lowers the barrier of entry to integrate it with existing JS codebases.
Miserlou
I’ll throw my hat into the ring too, I guess.
Just pushed an alpha of this:
https://github.com/Miserlou/live_json
Built for my own needs, but maybe it’ll be handy for you as well.
It’s very simple and works with existing LiveViews - just use LiveJson.push_patch the way you’d use assign or push_event. It has two modes, jsondiff and rfc mode, which use Jsondiff and JSON-Patch, respectively. jsondiff mode is very fast, and rfc mode is compatible everywhere.
As an example you can:
def handle_info({:new_data_to_visualize, new_data} = _event, socket) do
{:noreply,
socket
|> push_patch("viz_data", new_data)
}
end
Then, in your JS console:
window.viz_data
// {1: ["a"], 2: ["b"] ... 99999: ["zzzzz"]}
Only deltas are sent over the wire, so it’s quite fast!
More details soon, but works for me.








