Umbro
Umbro

Reputation: 2204

The socket.io connection returns an empty array. Ways to receive data in React without reloading the page?

I create a chrome extension in React. I am trying to download data via socket.io. I didn't get any errors, but the array is empty.

I should set the header and token, but I do not know where to do it in the app.js server. Where can I set:

const token = '12345'

headers: {
  'Authorization': `Bearer $ {token}`
}

How can I set port in server app.js and endpoint in client app.jsx if I create chrome extension?

Is there any other way (other than socket.io) to receive data in the method componentDidMount() in React without reloading the page?

When I go to the address http://127.0.0.1:4001, the console.log displays to me New client connected and Error: undefined

Server

//app.js

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001;/How port in `chrome extension?`
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
const token = "12345"; 


let interval;
io.on("connection", socket => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 10000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
  });
});

const getApiAndEmit = async socket => {
    try {
      const res = await axios.get(
        "https://b.application.com/api/v1/scores?expand=createdBy"
      ); // Getting the data from DarkSky
      socket.emit("FromAPI", res.data); // Emitting a new message. It will be consumed by the client
    } catch (error) {
      console.error(`Error: ${error.code}`);
    }
  };

server.listen(port, () => console.log(`Listening on port ${port}`));

//index.js

const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
  res.send({ response: "I am alive" }).status(200);
});
module.exports = router;

Client

//app.jsx

import socketIOClient from "socket.io-client";

class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      scores: []
      endpoint: "http://127.0.0.1:4001" /How endpoint in `chrome extension`?
    }
  }

componentDidMount() {
  const { endpoint } = this.state;
  const token = "12345"; 

  const socket = socketIOClient(endpoint);

  socket.on("FromAPI", data => this.setState({ todos: data }));
}


  render () {
      <div>
      </div>
    )
  }
}

export default App;

Upvotes: 2

Views: 1463

Answers (3)

Umbro
Umbro

Reputation: 2204

I solved it:

const getApiAndEmit = async socket => {
    try {
      const res = await axios.get(
        "https://b.application.com/api/v1/scores?expand=createdBy",
         headers: {
           Authorization: `Bearer ${token}`
         }
      ); 
      socket.emit("FromAPI", res.data); // Emitting a new message. It will be consumed by the client
    } catch (error) {
      console.error(`Error: ${error.code}`);
    }
  };

Upvotes: 6

Piyush
Piyush

Reputation: 139

-----------Try Replacing app.js:- -----------------

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const port = process.env.PORT || 4001;/How port in `chrome extension?`
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server); // < Interesting!
const token = "12345"; 
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});
let interval;
io.on("connection", socket => {
  console.log("New client connected");
  if (interval) {
    clearInterval(interval);
  }
  interval = setInterval(() => getApiAndEmit(socket), 10000);
  socket.on("disconnect", () => {
    console.log("Client disconnected");
  });
});

const getApiAndEmit = async socket => {
    try {
        const res = await axios("https://b.application.com/api/v1/scores?expand=createdBy", {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                "Access-Control-Allow-Origin": "*",
                'token': token
            }
        }); // Getting the data from DarkSky
        console.log("res.data:- "+JSON.stringify(res.data,null,4));
        socket.emit("FromAPI", res.data);  // Emitting a new message. It wil be consumed by the client
    } catch (error) {
        console.error(`Error: ${error.code}`);
    }
};

server.listen(port, () => console.log(`Listening on port ${port}`));

Upvotes: 4

Piyush
Piyush

Reputation: 139

Try modifying app.jsx as:

import socketIOClient from "socket.io-client";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            scores: [],
            receivedData:[],
            endpoint: "https://b.application.com/api/v1/scores?expand=createdBy",
            token: "12345"
        }
        this.onDataReceived = this.onDataReceived.bind(this);
        this.socket = socketIOClient(this.state.endpoint, {
            extraHeaders: {
                Authorization: `Bearer ${this.state.token}`
            }
        });
        this.socket.on("FromAPI", this.onDataReceived);
    }
    onDataReceived(receivedData) {
        console.log("receivedData ", receivedData);
        this.setState({
            receivedData: receivedData
        });
    }
        render() {
            return(
                <div></div>
            )
    }
}
export default App;

Try modifying app.js: function getApiAndEmit

replace the line: socket.emit("FromAPI", res.data);

io.emit("FromAPI", res.data);

Upvotes: 0

Related Questions