reactjssails.jssails.io.jssocket.io-client

Listening to sails socket in react


I'm trying to listen to changes from Sails socket in the front-end using react.

Server listen to changes in a MongoDB Collection and blasts the changes:

// Setting up connection to MongoDB
const RTPEntryDB = sails.getDatastore("RTPEntrydb").manager;
// Switching to the appropriate collection in MongoDB
const profilesCollection = RTPEntryDB.collection("workloads");

// MongoDB Change Stream - Detect changes in DB's collection
const changeStream = profilesCollection.watch();
changeStream.on("change", function(change) {
    console.log("new change", change);
    sails.sockets.blast('newWorkloads', change);
})

This is working perfectly fine.

But on the front-end, I couldn't listen

import React, { useRef, useReducer, useEffect } from 'react';
import PropTypes from 'prop-types';

import socketIOClient from 'socket.io-client';
import sailsIOClient from 'sails.io.js';


const FetchWorkloads = (props) => {

    // Instantiate the socket client (`io`)
    const io = sailsIOClient(socketIOClient);
    io.sails.url = 'http://localhost:1337/';

    io.socket.on('connect', function onConnect(){
        console.log('This socket is now connected to the Sails server!');
    });

    io.socket.on('newWorkloads', (msg) => {
        console.log('workloads changed', msg);
    });
    
    return (
        <>
            {/* My Component */}
        </>
        
    );
}

FetchWorkloads.propTypes = {
    api: PropTypes.object.isRequired
};

export default FetchWorkloads;

I'm getting the error GET http://localhost:1337/__getcookie net::ERR_ABORTED 404 (Not Found). How do I resolve this?

Thanks


Solution

  • I resolved this by defining a custom __getcookie in routes.js as follows:

    'GET /__getcookie': (req, res) => {
            return res.send('_sailsIoJSConnect();');
     },
    

    There was also another issue with the compatibility between sails.io.js and socket.io-client. I was using the latest version of socket.io-client (v4.4) but sails was only compatible with v2.x.