Cole
Cole

Reputation: 898

React-native Redux socket.io session authentication

any suggestions on connecting redux/react-native to socket.io after an http request? I need to make the http request first to store an auth session cookie, then connect to socket.io. All the examples I've seen (i.e https://www.npmjs.com/package/redux-socket.io) connect to socket.io right away. My thinking is listen to actions and connect like so in custom redux middleware:

import React from 'react-native'
import * as actions from './actions/';
import io from 'socket.io-client/socket.io';

export default socketMiddleware = (store) => {
    return next => action => {
    const result = next(action);
    // var socket = io();
    //
    if (action.type === 'HTTP_CONNECT_SUCCEEDED') {
      debugger;
      const socket = io('localhost:3000', {jsonp: false);
      socket.on('connect', function(){console.log('Connected!')});
    }
    //
    // socket.on('message', data => {
    //   store.dispatch(actions.addResponse(data));
    // });
    //
    // if (socket && action.type === actions.ADD_MESSAGE) {
    //   let messages = store.getState().messages;
    //   socket.emit('message', messages[messages.length -1]);
    // }

    return result;
  };
}

This works to connect, but I have to define my socket inside the 'HTTP_CONNECT_SUCCESS' conditional, and so my other socket actions and events are undefined until that action happens. How can I connect to WS on an action and also expose my socket events and other actions?

Upvotes: 4

Views: 907

Answers (1)

Cole
Cole

Reputation: 898

My hopefully temporary hack is to make my socket variable global, and wrap events in a conditional:

import React from 'react-native'
import * as actions from './actions/';
import io from 'socket.io-client/socket.io';

export default socketMiddleware = (store) => {
  return next => action => {

    const result = next(action);
    globalSocket = typeof globalSocket === 'undefined' ? false : globalSocket

    if (action.type === 'HTTP_CONNECT_SUCCEEDED') {
      globalSocket = io('http://localhost:3000', {jsonp: false});
      globalSocket.on('connect', () => {
        console.log('Connected!')
      });
    }

    if (globalSocket != false) {
      globalSocket.on('friends', data => {
        store.dispatch(actions.updateFriends(data));
      })

      if (action.type === 'CREATE_QUESTION') {
        globalSocket.emit('createQuestion', action.question);
      }
    }

    return result;
  };
}

Upvotes: 0

Related Questions