Skip to content

Instantly share code, notes, and snippets.

@bnhansn
Created October 22, 2016 18:08
Show Gist options
  • Save bnhansn/d7a4ecddd8477f9649b453b0824521bf to your computer and use it in GitHub Desktop.
Save bnhansn/d7a4ecddd8477f9649b453b0824521bf to your computer and use it in GitHub Desktop.
import { reset } from 'redux-form';
import { Presence } from 'phoenix'; // new line
// new function
const syncPresentUsers = (dispatch, presences) => {
const presentUsers = [];
Presence.list(presences, (id, { metas: [first] }) => first.user)
.map(user => presentUsers.push(user));
dispatch({ type: 'ROOM_PRESENCE_UPDATE', presentUsers });
};
export function connectToChannel(socket, roomId) {
return (dispatch) => {
if (!socket) { return false; }
const channel = socket.channel(`rooms:${roomId}`);
let presences = {}; // new line
// new function
channel.on('presence_state', (state) => {
presences = Presence.syncState(presences, state);
syncPresentUsers(dispatch, presences);
});
// new function
channel.on('presence_diff', (diff) => {
presences = Presence.syncDiff(presences, diff);
syncPresentUsers(dispatch, presences);
});
channel.on('message_created', (message) => {
dispatch({ type: 'MESSAGE_CREATED', message });
});
channel.join().receive('ok', (response) => {
dispatch({ type: 'ROOM_CONNECTED_TO_CHANNEL', response, channel });
});
return false;
};
}
// ...rest of file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment