react-native: import syntax throws when importing socket.io if debugger is not attached
I don’t know how to even begin with this one, but I’m including Socket.IO into a project spawned from react-native init. The import of the SocketIO library bombs, but only when the debugger is not attached. I can use the require syntax instead and then that works no matter what.
Always works:
let io = require('socket.io-client/socket.io');
Fails with Chrome Debugging disabled but works otherwise:
import io from 'socket.io-client/socket.io';
Here’s the error for whatever good it is: “undefined is not an object (evaluating navigator.userAgent.match)”
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 1
- Comments: 45 (26 by maintainers)
@Mokto Try this:
@tarkanlar
The code that works:
you have to write “ws://” instead of “http://”. And add “transports: [‘websocket’]”. It should works.
@chezhe thanks so much, it works like a charm ! I’ve been looking for solution and no hope until i saw this xD
@adamterlson I can confirm that i’ve used socket.io with react native and had no issues.
The only caveat that I ran into earlier was that
userAgent
was undefined. I managed a temporary work around by addingwindow.navigator.userAgent = "react-native";
Here is an article by @browniefed that might help. http://browniefed.com/blog/2015/05/16/react-native-and-socket-dot-io/
In the past i’ve worked with https://www.npmjs.com/package/react-native-swift-socketio and it worked fine as well.
Hope this helps!
@adamterlson As far as I understand, all imports are hoisted to the top, while requires are not. Hence, the reason it’s not working with
import
syntax is,socket.io
is being required and executed even beforewindow.navigator.userAgent = "react-native"
is called, and throws error.I guess it only happens in debugger because there might be a delay somewhere while communicating via the bridge, and there is not enough delay when running on phone to cause this. I might be wrong though.
Feel free to close the issue if this answers your question.
@christopherdo Well Socket IO works fine, but that’s not really the issue. The question is why there’s inconsistent behavior from RN depending on
import
vsrequire
usage and whether a debugger is attached. Does that not seem strange?Thanks for the help!