Ad

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;
Ad

Answer

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}`);
    }
  };
Ad
source: stackoverflow.com
Ad