jeudi 4 juin 2020

Socket.io is not emitting or listening to events in react.js

The problem is that I just want to create one instance of socket.io-client and share that to multiple components by importing the instance. But after importing I am getting the instance but it does not invoke any events.

Here is my utils function to instantiate the socket in client-side:(React.js)

// socket.js
import io from 'socket.io-client'
const socket = io('http://localhost:8810')
export default socket;

Here is my component file: let say notification.js
// Importing
import socket from '../utils/socket'

class Notifications extends Component {
  constructor(props) {
    super(props);
    this.state = {
      socket: socket,
      // socket: io("http://localhost:8810"), // WHEREAS THIS WORKS FINE BUT I 
      // HAVE TO CONNECT TO SOCKET EACH TIME IF I USE THIS
      showNotification: false,
      customNotifications: [],
      username: 'test'
    };
  }
   componentDidMount() {
    // HERE FETCH NOTIFICATION FROM DB
    console.log("Socket instance ", this.state.socket) // SHOWN BELOW IN SCREENSHOT

    // IT"S NT GETTING INVOKED
    this.state.socket.on("connect", () => {
     console.log(
       "Your socket is successfully set up!"
     );

     this.state.socket.on('user connected', () => {
       console.log('user connected message!')
       addToNotification({
         imgSrc: donutIcon,
         heading: 'Welcome to donut!',
         content: 'Nice to see you here!',
         tag: 'Welcome'
       })
     })

     this.state.socket.emit("new user connected", {
       username: state.username
     });
   });
  }
}

SCREENSHOT SHOWING CONSOLE.LOG socket instance console.log('socket instance')




Aucun commentaire:

Enregistrer un commentaire