I am getting a null .onmessage
but .onopen is working
import * as types from './types';
import { eventChannel } from 'redux-saga';
import { takeEvery, put, call, select, take } from 'redux-saga/effects';
export function* createEventChannel() {
const mySocket = new WebSocket('wss://url.com');
return eventChannel((emit: any) => {
mySocket.onopen = () => {
mySocket.send("sdsdsdsd!");
};
// =====> onmessage is getting null
mySocket.onmessage((message:any) => {
emit(message.data)
});
return () => {
mySocket.close();
};
});
}
export function* workWebSocket(action:any) {
const channel = yield call(createEventChannel);
while (true) {
const { message } = yield take(channel);
yield put({ type: types.WEB_SOCKET_SUCCESS, message: message });
}
}
export default function* watchHydration() {
yield takeEvery(types.WEB_SOCKET_FETCH, workWebSocket);
}
Any suggestions on why I am getting null?
look at this example: could you parse the data properly?
function initWebsocket() {
return eventChannel(emitter => {
ws = new WebSocket(wsUrl + '/client')
ws.onopen = () => {
console.log('opening...')
ws.send('hello server')
}
ws.onerror = (error) => {
console.log('WebSocket error ' + error)
console.dir(error)
}
ws.onmessage = (e) => {
let msg = null
try {
msg = JSON.parse(e.data)
} catch(e) {
console.error(`Error parsing : ${e.data}`)
}
if (msg) {
const { payload: book } = msg
const channel = msg.channel
switch (channel) {
case 'ADD_BOOK':
return emitter({ type: ADD_BOOK, book })
case 'REMOVE_BOOK':
return emitter({ type: REMOVE_BOOK, book })
default:
// nothing to do
}
}
}
// unsubscribe function
return () => {
console.log('Socket off')
}
})
}
export default function* wsSagas() {
const channel = yield call(initWebsocket)
while (true) {
const action = yield take(channel)
yield put(action)
}
}