Skip to content

futpib/redux-phoenix-middleware

Repository files navigation

redux-phoenix-middleware

Declarative automatic bidirectional maping between Redux Actions and Phoenix Channel Messages

Build Status Coverage Status

Example

import {
	createPhoenixReducer,
	createPhoenixMiddleware,
	phoenixSocketStateSelector,
	phoenixChannelStateSelector,
	phoenixEventActionType,
} from 'redux-phoenix-middleware';

const phoenixReducer = createPhoenixReducer();
const phoenixMiddleware = createPhoenixMiddleware({
	sockets: {
		// You can specify one or many sockets here, each under a unique key
		socket: {
			// Sockets are automatically connected by default
			endPoint: BASE_URL + '/socket',
			channels: {
				// Channels are automatically joined (once the socket is connected) by default
				'room:lobby': true,
			},
		},
	},
});

// Keeps a log of messages sent to the `lobby` room
const messagesReducer = (state = [], action) => {
	// Got a channel event, could've been sent like `broadcast!(socket, "message", %{ ... })`
	if (action.type === phoenixEventActionType('socket', 'room:lobby', 'message')) {
		return state.concat(action.payload);
	}

	return state;
};

const store = createStore(combineReducers({
	messages: messagesReducer,
	phoenix: phoenixReducer,
}), initialState, applyMiddleware(phoenixMiddleware));

// Somewhere else:

const state = store.getState();

phoenixSocketStateSelector(state.phoenix, 'socket') === 'open'; // or 'closed'
phoenixChannelStateSelector(state.phoenix, 'socket', 'room:lobby') === 'joined'; // or 'closed', 'errored'

Install

yarn add redux-phoenix-middleware

About

Declarative automatic bidirectional maping between Redux Actions and Phoenix Channel Messages

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published