简体   繁体   中英

React JS socket on event doesn't trigger

I have an Express.js backend and a React front end.

I install the socket.io on the backend.

App.js

 const server = app.listen(port, () => { console.log(`Server started on port, ${port} ${process.env.NODE_ENV}`); }); const io = socket(server); io.on('connection', (socket) => { console.log('connected',socket.id) socket.on('infoListUpdate', function () { socket.broadcast.emit('updateInfoList'); console.log('jj') }); socket.on('docsListUpdate', function () { socket.broadcast.emit('updateDocsList',{}); console.log('emited') }); });

In React I have

Company.js

 export default function Company(props) { return ( <Fragment> <Agent {...props} /> <CreateDocs {...props} /> <CreateInfo {...props} /> </Fragment> ); }

In the CreateDocs component, I do this

 socket.emit('docsListUpdate')

Then I can see the "emitted" is printing on the console.log of the backend. So I think emitting from the front end to the backend part is working.

Then Agent component I added this to listen to that event

 socket.on('updateDocsList',(data)=>{
    console.log('i am here')
  })

"i am here" part is never printing.

In the React front end, I created a socket.js file and import the socket from that file to the components.

const io = require('socket.io-client');
const baseURL =process.env.REACT_APP_BE_URL;

const socket = io.connect(baseURL,{
    transports:['websocket']
})

export default socket;

What's wrong in my code?

I change this socket.broadcast.emit('updateDocsList',{}); to socket.emit('updateDocsList',{});

Reason:- Broadcast will emit for all except to the sender.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM