Last active
November 9, 2023 12:21
-
-
Save dcarneiro/353c4706890906a0391dea1115ac7971 to your computer and use it in GitHub Desktop.
connect redux-saga to phoenix channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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