Skip to content

Instantly share code, notes, and snippets.

@dhamkur
Created April 14, 2022 08:14
Show Gist options
  • Save dhamkur/c6ee2021c7892217e2db1153a557f375 to your computer and use it in GitHub Desktop.
Save dhamkur/c6ee2021c7892217e2db1153a557f375 to your computer and use it in GitHub Desktop.
import ActionCable from "actioncable";
import { ActionCableProvider } from "react-actioncable-provider";
import cookie from "js-cookie";
import constants from "@/libs/constants";
import { useState, useEffect } from "react";
import "react-notifications/lib/notifications.css";
import {
NotificationContainer,
NotificationManager,
} from "react-notifications";
const cable = ActionCable.createConsumer(
constants.WEB_SOCKET_ENDPOINT + "?token=" + sessionStorage.getItem("token"),
);
const WebSocket = () => {
const [hide, setHide] = useState(false);
const [connected, isConnected] = useState(false);
const [disconnected, isDisconnected] = useState(false);
const handleReceived = (data) => {
setHide(true);
NotificationManager.info(data.message, data.title, 3000, () => {
hide;
});
};
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
if (cookie.get("token") != undefined) {
cable.subscriptions.create("NotificationChannel", {
connected: function () {
// Called when the subscription is ready for use on the server
isConnected(true);
},
disconnected: function () {
// Called when the subscription has been terminated by the server
isDisconnected(this.consumer.connection.disconnected);
},
received: function (data) {
// Called when the subscription has been received data by the server
handleReceived(data);
},
});
}
return () => {
disconnected;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{connected ? (
<ActionCableProvider cable={cable}>
<NotificationContainer />
</ActionCableProvider>
) : (
<p>Notification disconnected...</p>
)}
</>
);
};
export default WebSocket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment