Apollo subscriptions - handling WS disconnects with subscribeToMore - javascript

I've been looking for a way to handle web socket disconnects in my React app with Apollo subscriptions and have not found a way to do so. The other examples I see in the apollo documentation show the below method for catching a reconnect:
const wsClient = process.browser ? new SubscriptionClient(WSendpoint, {
reconnect: true,
}) : null;
const wsLink = process.browser ? new WebSocketLink(wsClient) : null;
if (process.browser) {
wsLink.subscriptionClient.on(
'reconnected',
() => {
console.log('reconnected')
},
)
}
There are two issues with the above method:
is that is does not catch when the user disconnects from their internet (only from when the server restarts for whatever reason)
that the reconnect is triggered outside of my React apps components.
What I would like to be able to do is to is reload my "chat" component if the user either disconnects from their internet or if my express server goes down for any reason. For this to happen I would need my chat component to completely reload which i'm not sure would be possible from outside my component tree.
Is there a method in the Query or Subscription Apollo components to be able to capture this event and handle it accordingly from the component?

There are a few ways I can think of to handle these cases but none of them are a one-shot solution, each case needs to be handled independently.
Setup a online/offline listener (ref)
Setup an Apollo middleware to handle network errors from your server (ref)
Create a variable in your store, isOnline for example, which can hold a global reference of your app's state. Whenever the above two methods trigger, you could update the value of isOnline
Finally, to bundle all of it together. Create a react HOC which uses isOnline to handle the network state for each component. This can be used to handle network error messages, refresh components once network is restored.

You can use SubscriptionClient callbacks from subscriptions-transport-ws, like this:
const ws = require("ws");
const { SubscriptionClient } = require("subscriptions-transport-ws");
const { WebSocketLink } = require("apollo-link-ws");
const { ApolloClient } = require("apollo-client");
const { InMemoryCache } = require("apollo-cache-inmemory");
const subClient = new SubscriptionClient(
'ws://localhost:4000/graphql',
{ reconnect: true },
ws
);
subClient.onConnected(() => { console.log("onConnected") });
subClient.onReconnected(() => { console.log("onReconnected") });
subClient.onReconnecting(() => { console.log("onReconnecting") });
subClient.onDisconnected(() => { console.log("onDisconnected") });
subClient.onError(error => { console.log("onError", error.message) });
const wsLink = new WebSocketLink(subClient);
const client = new ApolloClient({
link: wsLink,
cache: new InMemoryCache()
});
I'm using this for Node.js, but it will probably work for React too.

Related

Simulate actioncable websocket receive in webdriverIo

Is there a way during webdriverio runtime to simulate an actioncable receive?
I am using a fork of the package action-cable-react called actioncable-js-jwt for Rails actioncable js connections. Both of these packages are no longer maintained, but actioncable-js-jwt was the only actioncable for react package I could find that supported jwt authentication. I am building an app in my company's platform and jwt authentication is required.
The problem I am running into is that I have a react component which dispatches a redux action to call an api. The api returns a 204, and the resulting data is broadcasted out from Rails to be received by the actioncable connection. This triggers a dispatch to update the redux store with new data. The component does actions based on new data compared to the initial value on component load, so I cannot simply just set initial redux state for wdio - I need to mock the actioncable receive happening.
The way the actioncable subscription is created is:
export const createChannelSubscription = (cable, receivedCallback, dispatch, channelName) => {
let subscription;
try {
subscription = cable.subscriptions.create(
{ channel: channelName },
{
connected() {},
disconnected(res) { disconnectedFromWebsocket(res, dispatch); },
received(data) { receivedCallback(data, dispatch); },
},
);
} catch (e) {
throw new Error(e);
}
return subscription;
};
The receivedCallback function is different for each channel, but for example the function might look like:
export const handleUpdateRoundLeaderWebsocket = (data, dispatch) => {
dispatch({ type: UPDATE_ROUNDING_LEADER, round: data });
};
And the redux state is used here (code snippets):
const [currentLeader, setCurrentLeader] = useState(null);
const userId = useSelector((state) => state.userId);
const reduxStateField = useSelector((state) => state.field);
const onChange = useCallback((id) => {
if (id !== currentLeader) {
if (id !== userId && userId === currentLeader) {
setShow(true);
} else {
setCurrentLeader(leaderId);
}
}
}, [currentLeader, userId]);
useEffect(() => {
onChange(id);
}, [reduxStateField.id, onChange]);
Finally, my wdio test currently looks like:
it('has info dialog', () => {
browser.url('<base-url>-rounding-list-view');
$('#my-button').click();
$('div=Continue').click();
// need new state after the continue click
// based on new state, might show an info dialog
});
Alternatively, I could look into manually updating redux state during wdio execution - but I don't know how to do that and can't find anything on google except on how to provide initial redux state.

How to use STOMP for connecting with ActiveMQ in React js

Can anyone provide successful implementation of Stomp using the latest version of ActiveMQ 5.x using the React N? How to connect and publish to the queue?
I have below questions:
I have to retrieve the data from consumer and do some add some boolean value and send it to publish.
How can I keep the connection alive because continuously I will get message in queues.
How can I implement this in React.js in simple manner (any plugins)
I tried with JavaScript, and it works as expected.
consumer.js
const Stomp = require("stomp-client");
const stompClient = new Stomp("127.0.0.1",61613);
stompClient.connect( function(sessionId){
console.log("consumer connected");
stompClient.subscribe("/queue/<name>",function(body){
console.log(body);
});
});
producer.js
const Stomp = require("stomp-client");
const stompClient = new Stomp("127.0.0.1",61613);
stompClient.connect( function(sessionId){
console.log("producer connected");
stompClient.publish("/queue/<name>",function(body){
console.log(body);
console.log(typeof(body));
//JSON.stringify(body);
});
stompClient.disconnect();
});
This is what I tried in React.JS (which failed): here i can able to connect and after that if i call subscribe with que name it is not giving any response
import './App.css';
import React,{useEffect} from 'react';
import { Client, Message } from '#stomp/stompjs';
function App() {
const clientdata = new Client();
useEffect(() => {
clientdata.configure({
brokerURL: 'ws://localhost:61614/stomp',
onConnect: (frame) => {
console.log('onConnect');
console.log(frame);
clientdata.subscribe('/queue/<quename>',info => {
console.log(info);
})
console.log(subscription);
},
// Helps during debugging, remove in production
debug: (str) => {
// console.log(new Date(), str);
}
});
client.activate();
}, []);
return (
<div >
</div>
);
}
export default App;
When i tried the above code I am getting only connected log and I'm not able to subscribe any thing and not seeing anything.

socket io to much rerendering in react

I'm using socketio and react. Im trying to set state for all users when one use changes it but it causes too much rerendering on site.
server.js
const app = require('express')
const http = require('http').createServer(app)
const io = require("socket.io")(http, {
cors: {
origin: "http://localhost:3000",
},
});
let subject = ''
io.on('connection', (socket) => {
socket.on('setSubject', (sbj) => {
subject = sbj
io.sockets.emit('getSubject',subject)
})
socket.on('changeHiddenPassword',hiddenPassword => {
socket.broadcast.emit('newHiddenPassword',hiddenPassword)
})
})
http.listen(4001,function(){
console.log('listening on port 4001')
})
front end
const [hiddenPassword,changeHiddenPassword] = useState([''])
useEffect(() => {
socket.emit('changeHiddenPassword',hiddenPassword)
}, [hiddenPassword]);
socket.on('newHiddenPassword',newHiddenPassword => {
changeHiddenPassword(newHiddenPassword)
})
I dont think rest of the code will help you somehow but if it would i can provide it to you. What i'm trying to do is when someone clicks on specific element on my site i want my hiddenPasword state to change for all connected users. I know that what i'm doing is wrong,beacouse when the state changes for one user useEffect is passing and setting state to everyone else and their useEffect are passing and setting state to everyone else and so on... I want to know how to do it properly and i cant figure out how.
so when you change hiddenPassword you are emitting changeHiddenPassword event, this sends back newHiddenPassword event which changes the hiddenPassword and this continues infinitely.
Try modifying newHiddenPassword handler like this, so it's not changing the state (and triggering useEffect) when the received password is already up to date
socket.on('newHiddenPassword',newHiddenPassword => {
if (newHiddenPassword !== hiddenPassword) {
changeHiddenPassword(newHiddenPassword);
}
});

socket io event fires multiple times

I have searched similar questions here but none of them work for me.
I know some people recommend not to use socket inside another event but I had no clue how to trigger socket whenever there is an event.
So I have initialized socket inside another event which is updated every time something happens. But socket connection repeats the previous result with every new update.
I tried initializing socket within componentDidMount lifecyle and it simply does not work.
class UploadComponent extends Component {
constructor (props) {
super(props);
this.state = {
endpoint: "http://localhost:3000",
}
this.uploadModal = this.uploadModal.bind(this);
}
uploadModal () {
update.on('success', file => {
let {endpoint} = this.state;
let socket = socketIOClient(endpoint, {transports: ['websocket', 'polling', 'flashsocket']});
socket.on('data', (mydata) => {
console.log(mydata) // <-- This gets fired multiple times.
})
})
}
// some more code //
}
I want to trigger socket whenever "update" event is fired without message duplication.
As sockets are emitting multiple times on Angular with nodejs happened the same with me for sockets, i tried by removing the socket listeners by this.socket.removeListener( "Your On Event" );,
This helped me solved the issue of multiple socket calls, try it, it may help !
Unless you can guarantee success is called only once, then you'll need to initialize the socket connection / event handler outside this function
class UploadComponent extends Component {
constructor (props) {
super(props);
const endpoint = "http://localhost:3000";
this.state = { endpoint };
this.uploadModal = this.uploadModal.bind(this);
this.socket = socketIOClient(endpoint, {transports: ['websocket', 'polling', 'flashsocket']});
this.socket.on('data', (mydata) => {
console.log(mydata)
})
}
uploadModal() {
update.on('success', file => {
// this.socket.emit perhaps?
})
}
}
As James have suggested I have put my socket logic in the constructor. But it was only being fired after my component remounts.
After looking at my nodejs server code I tried to replace
// some code //
io.on('connection', (client) => {
client.emit('data', {
image: true,
buffer: imageBuffer.toString('base64'),
fileName: meta.name
})
})
with this
// some code //
io.emit('data', {
image: true,
buffer: imageBuffer.toString('base64'),
fileName: meta.name
})
and it works!
Also I had to close socket in componentWillUnmount to avoid multiple repeated data.

Flux and WebSockets

I'm using Flux and WebSocket in my Reactjs application and during implementation I've encountered some problems.
Questions:
Assuming I have a set of a set of actioncreators and a store for managing the WebSocket connection, and that the connection is started in a actioncreator (open(token)), where should I put my conn.emit's and how do I get other actions access to my connection object so that they can send data to the backend?
Do I have to pass it as an argument to the actions that are called in the views (eg. TodoActions.create(conn, todo)) or is there a smarter way?
Current code is here
I'm using ES6 classes.
If I have omitted anything necessary in the gist, please let me know.
EDIT:
This is what I have concocted so far based on glortho's answer:
import { WS_URL } from "./constants/ws";
import WSActions from "./actions/ws";
class WSClient {
constructor() {
this.conn = null;
}
open(token) {
this.conn = new WebSocket(WS_URL + "?access_token=" + token);
this.conn.onopen = WSActions.onOpen;
this.conn.onclose = WSActions.onClose;
this.conn.onerror = WSActions.onError;
this.conn.addEventListener("action", (payload) => {
WSActions.onAction(payload);
});
}
close() {
this.conn.close();
}
send(msg) {
return this.conn.send(msg);
}
}
export default new WSClient();
You should have a singleton module (not a store or an action creator) that handles opening the socket and directing traffic through. Then any action creator that needs to send/receive data via the socket just requires the module and makes use of its generic methods.
Here's a quick and dirty untested example (assuming you're using CommonJS):
SocketUtils.js:
var SocketActions = require('../actions/SocketActions.js');
var socket = new WebSocket(...);
// your stores will be listening for these dispatches
socket.onmessage = SocketActions.onMessage;
socket.onerror = SocketActions.onError;
module.exports = {
send: function(msg) {
return socket.send(msg);
}
};
MyActionCreator.js
var SocketUtils = require('../lib/SocketUtils.js');
var MyActionCreator = {
onSendStuff: function(msg) {
SocketUtils.send(msg);
// maybe dispatch something here, though the incoming data dispatch will come via SocketActions.onMessage
}
};
Of course, in reality you'll be doing better and different things, but this gives you a sense of how you might structure it.

Categories

Resources