phux
v0.2.0
Published
Client-side Phoenix Channels with Redux
Downloads
4
Readme
Phux
Client-side Phoenix Channels
Built for Ckd
Getting Started
yarn add phux
Client-side:
import phux from "phux"
const BlogPostsChannel = {
api: "v0:posts",
initialState: {
loaded: false,
posts: [],
currentPage: 1,
},
reducer(state, msg) {
switch (msg.type) {
case "POSTS":
return { ...state, posts: msg.payload.posts, loaded: true }
case "PAGE_CHANGE":
return { ...state, currentPage: msg.payload.pageNumber, loaded: false }
default:
return state
}
},
methods: {
goToNextPage({ push, state }) {
push("PAGE_CHANGE", { pageNumber: state.currentPage + 1 })
},
},
}
const myAppClient = phux({
channels: [BlogV0ListPostsChannel],
})
const myApp = myAppClient(
{
socketUrl: "ws://localhost:1818/socket",
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
},
({ connected }) => {}
)
myApp.connect()
const ch = myApp.posts.channel(
({ loaded, posts, currentPage, goToNextPage }) => {}
)
ch.read() // => { loaded, posts, currentPage, goToNextPage }
ch.leave()
myApp.disconnect()
Server-side:
defmodule MyAppWeb.Blog.V0.PostsChannel do
use Phoenix.Channel
@initial_page 1
def join("v0:posts", _message, socket) do
send(self(), :after_join)
{:ok, assign(socket, current_page: @initial_page)}
end
def handle_info(:after_join, socket) do
push("POSTS", %{posts: get_page(socket.assigns.current_page)})
{:noreply, socket}
end
def handle_in("PAGE_CHANGE", %{"page" => page}, socket) do
socket = assign(socket, current_page: page)
push("POSTS", %{posts: get_page(socket.assigns.current_page)})
{:noreply, socket}
end
defp get_page(n) do
[
%{title: "Hello World #{n}", body: "👋"}
]
end
end