问题
I am trying to create a socket connection in my react/redux web application and I am trying to initialize a socket connection only when a user is logged in. My socket instance currently resides in a middleware but when I try to check if a user is logged, I get an error like this Uncaught TypeError: Cannot read property 'apply' of undefined
. Here is the snippet of the middleware code:
const socketMiddleWare = url => store => {
if (store.getState().user.username) {
const socket = new SockJS(url, [], {
sessionId: () => custom_token_id
});
socket.onopen = e => {
console.log("Connection", e.type);
if (e.type === "open") {
store.dispatch({ type: types.TOGGLE_SOCK_OPENED });
createSession(custom_token_id, store);
}
};
socket.onclose = () => {
console.log("Connection closed");
};
socket.onmessage = e => {
const message = JSON.parse(e.data);
};
return next => action => {
if (
action.type === types.SEND_SOCKET_MESSAGE
) {
socket.send(JSON.stringify(action.payload));
return;
} else if (action.type === types.USER_LOGGED_OUT) {
socket.close();
}
next(action);
};
}
};
`
`
const middleWare = applyMiddleware(
routerMiddleware(history),
sagaMiddleware,
promise(),
thunk,
socketMiddleWare(`${config("LOCALHOST").url}`)
);
`
`
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(
rootReducer,
persistedState,
composeEnhancers(middleWare)
);
Thanks.
来源:https://stackoverflow.com/questions/52269348/initialize-socket-connection-only-when-a-condition-is-met