IgorYzk
IgorYzk

Reputation: 31

How to establish connection in socket.io-client and react?

I have an issue with using socket.io-client with react. Im just starting how to use it so i wanted to display a message in console when there is a connection but nothing appears in console. Yes i have both react app and server running.

server.js

const app = require('express')

const http = require('http').createServer(app)
const io = require('socket.io')(http)

let subject = ''

io.on('connection', (socket) => {
    console.log('ahoj')
    
})

http.listen(4001,function(){
    console.log('listening on port 4001')
})

App.js

import './App.css';
import CreateSubject from './components/CreateSubject'
import Hangman from './components/Hangman'
import { HangmanProvider } from './context/HangmanContext'
import io from 'socket.io-client'

io.connect('http://localhost:4001')



function App() {
  return (
    <HangmanProvider>
      <div className="App">
        <CreateSubject/>
        <Hangman/>
      </div>
    </HangmanProvider>
  );
}

export default App;

expected console.log

listening on port 4001
ahoj

my console.log

listening on port 4001

Upvotes: 1

Views: 363

Answers (1)

Israr Khan
Israr Khan

Reputation: 21

Add this to your server.js file to enable cors, here "3000" is the port where your React app is running.

const io = require("socket.io")(http, {
  cors: {
     origin: "http://localhost:3000",
  },
});

To your App.js file add these lines

 import socketIOClient from 'socket.io-client';
 const ENDPOINT = 'http://localhost:4001';

 useEffect(() => {
   const socket = socketIOClient(ENDPOINT);
   socket.onAny((event, ...args) => {
    console.log(event, args);
   });
 }, []);
 

Replace: import { io } from 'socket.io-client';

With: import socketIOClient from 'socket.io-client';

Upvotes: 1

Related Questions