0

I have the following senario where I would like to send a boolean value back to my component in React. I am able to emit and call my method inside my server.js, however I can't figure out how to send data back once it executes.

Server.js:

 ...

const io = require('socket.io')(server);

var fetch = () => {
  url = 'abc';
  request(url, function(error, response, html){

    ...

    fs.writeFile(__dirname + '/data/output.json', JSON.stringify(result, null, 4), function(err){
      if(err) {
        throw err;
      } else {
        console.log('File successfully written! - Check your project directory for the output.json file');

        io.on('connection', (socket) => {  
          console.log('send data back to component');
        });
      }
    });
  })
}

io.on('connection', (socket) => {  
  //console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on('fetchData', () => {
    fetch(); 
  });

});

Component.js (react)

...

handleClick() {
    socket.emit('fetchData');
  }


  render() {
    return (
      <div>
        <button onClick={(e) => this.handleClick(e)}>Fetch</button>
      </div>
    )    

}

1 Answer 1

2

First, in your fetch() function, you've listened to your connection once more. Second, I think you will need to add a listener on your component. e.g.

Server.js:

 var fetch = (socket) => {
  url = 'abc';
  request(url, function(error, response, html){

    ...

    fs.writeFile(__dirname + '/data/output.json', JSON.stringify(result, null, 4), function(err){
      if(err) {
        throw err;
      } else {
        console.log('File successfully written! - Check your project directory for the output.json file');
        var bool;
        socket.emit('get-data-back', bool);
      }
    });
  })
}

io.on('connection', (socket) => {  
  //console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on('fetchData', () => {
    fetch(socket); 
  });

});

Component:

    ...

    componentDidMount() {
      socket.on('get-data-back', (data) => {
        console.log(data);
      })
    }


    handleClick() {
        socket.emit('fetchData');
      }


      render() {
        return (
          <div>
            <button onClick={(e) => this.handleClick(e)}>Fetch</button>
          </div>
        )    
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I had to reconfig something in my server.js that I didnt post. That worked however, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.