This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io
Welcome back dear internet friend!
Having trouble getting started with WebSockets in React Native? I’ve got the answer you’re looking for! After many hours of messing around with WebSockets in React Native for the first time today I’ve made some discoveries that hopefully will be of use to someone else out there on the internet.
The next stumbling block you might run into is setting up your own WebSocket server. For me, this ended up being a lot trickier than simply setting up a WebSocket server for a web app. I have setup WebSocket servers for both NodeJS and Flask web apps fairly easily, but doing the same with React Native gave me a lot of problems. So what I found extremely helpful was to use a test endpoint from a 3rd party that simply echos back any WebSocket messages sent from my app.
After a days work fumbling around, riding the struggle bus, I present a super simple quick start template for getting up and running with WebSockets in React Native. The endpoint URL in the code points to the 3rd party WebSocket test endpoint described above, so the solution below should work as is with no modification necessary. Just create a new React Native app, delete the contents of your App.js file, and copy & paste the code below, and you should be well on your way! (and this way, you will know your React Native app is working properly and playing nice with WebSockets before you start messing around with your server side code. Also, remember to avoid Socket.IO if you want to use the built-in WebSocket API like in my example:
EDIT: According to notable developer Miguel Grinberg, Socket.IO will not fall back upon HTTP Long Polling in React Native if you specify that you want to use [websockets] as your transport method. But never let the truth get in the way of a good story, so I’m leaving this post unedited 😉