Skip to content

Instantly share code, notes, and snippets.

@dcarneiro
Last active November 9, 2023 12:21
Show Gist options
  • Save dcarneiro/353c4706890906a0391dea1115ac7971 to your computer and use it in GitHub Desktop.
Save dcarneiro/353c4706890906a0391dea1115ac7971 to your computer and use it in GitHub Desktop.
connect redux-saga to phoenix channel
function* connectToSocket(url) {
const socket = new Socket(socketBaseUrl() + url, { params: { token: 'your-auth-token' } });
socket.connect();
return socket;
}
// channel.join is async, this is probably an error
function* joinChannel(socket, channel_name) {
const channel = socket.channel(channel_name, {});
channel.join();
return channel;
}
// this function creates an event channel from a given socket
function createSocketChannel(channel) {
// `eventChannel` takes a subscriber function
// the subscriber function takes an `emit` argument to put messages onto the channel
return eventChannel(emit => {
const newStoryHandler = (event) => {
emit(newStoryReceived(event));
}
channel.on('new_story', newStoryHandler);
const unsubscribe = () => {
channel.off('new_story', newStoryHandler)
}
return unsubscribe;
});
}
function* handleNewStory(action) {
yield put(action);
}
function* connectToStoryChannel() {
const socket = yield call(connectToSocket, '/socket');
const channel = yield call(joinChannel, socket, 'rooms:lobby');
const socketChannel = yield call(createSocketChannel, channel);
while (true) {
const action = yield take(socketChannel)
yield fork(handleNewStory, action)
}
}
export function* getWatcher() {
yield fork(takeLatest, CONNECT_TO_STORY_CHANNEL, connectToStoryChannel);
}
export function* storiesSaga() {
// Fork watcher so we can continue execution
const watcher = yield fork(getWatcher);
// Suspend execution until location changes
yield take(LOCATION_CHANGE);
yield cancel(watcher);
}
@dcarneiro
Copy link
Author

Right now when a message is broadcasted, I get the following error on the saga:

uncaught at check Saga was provided with an undefined action
Hints:
    - check that your Action Creator returns a non-undefined value
    - if the Saga was started using runSaga, check that your subscribe source provides the action to its listeners

@dcarneiro
Copy link
Author

the problem was that newStoryHandler callback needed to return an action. The gist should be working right now although I don't like the join channel generator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment