Saturday, 6 July 2019

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 check the status in the network tab to see the code 200.

In network tab in headers I see:

Request URL: "https://b.application.com/api/v1/scores?expand=createdBy"
Request Method: POST
Status Code: 200 OK

In the response tab I see: This is a piece of code:

<! doctype html>
<html ng-app = "app">
<Head>
     <meta charset = "utf-8">
     <title page-title> </ title>
     <meta name = "viewport" content = "width = device-width, initial-scale = 1">

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}`
}

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

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;
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: "https://b.application.com/api/v1/scores?expand=createdBy"
    }
  }

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

  const socket = socketIOClient(endpoint, {
    extraHeaders: {
      Authorization: `Bearer ${token}`
    }
  });

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


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

export default App;



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

No comments:

Post a Comment