Initialize socket connection only when a condition is met

删除回忆录丶 提交于 2019-12-11 15:55:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!