0

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.

Dave Kalu
  • 1,520
  • 3
  • 19
  • 38
  • Is there a stack trace for the rest of the error? If so, can you post that? – markerikson Sep 11 '18 at 17:02
  • I managed to get it to work. What I did was to move the `return next => action` block outside the if block. But it is still not fixing the problem. What I'm trying to achieve is to create the socket instance only when a user has logged. At the moment, the socket instance gets created and the socket opens as soon as the application runs even if it is on the login page. Is there a way to have it initialized when the main application mounts and still have it accessible like it is now. – Dave Kalu Sep 11 '18 at 18:28
  • Sure - see the similar example I showed in https://stackoverflow.com/questions/52260906/custom-websocket-in-redux-architecture/52261542#52261542 . Run the socket setup logic based on some specific action type, like `"USER_LOGGED_IN"`. And yes, now that I look at it, your original middleware was only returning the rest of the middleware function _some_ of the time, so the rest of the time it was returning `undefined`. – markerikson Sep 11 '18 at 18:41

0 Answers0