jazst21
1/31/2019 - 4:47 AM

#socket.io #axios

#socket.io #axios

==================================================================    Client    App.js     ============================
import React, { Component } from "react";
import socketIOClient from "socket.io-client";

class App extends Component {
  constructor() {
    super();
    this.state = {
      response: false,
      endpoint: "http://127.0.0.1:4001"
    };
  }
  componentDidMount() {
    const { endpoint } = this.state;
    const socket = socketIOClient(endpoint);
    socket.on("FromAPI", data => this.setState({ response: data }));
  }

  render() {
    const { response } = this.state;
    return (
      <div style={{ textAlign: "center" }}>
        {response
          ? <p>
              The temperature in Florence is: {response} °F
            </p>
          : <p>Loading...</p>}
      </div>
    );
  }
}

export default App;
==================================================================    Server   ./server/serer.js      ============================
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const axios = require("axios");
const router = express.Router();
const port = process.env.PORT || 4001;
//const index = require("./routes/index");

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

const server = http.createServer(app);
const io = socketIo(server);

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

const getApiAndEmit = async socket => {
  try {
    const res = await axios.get(
      "https://api.darksky.net/forecast/f3f49b12e44c88aadd26e014f22c3ef5/42.3601,-71.0589"
    );
//    socket.emit("FromAPI", res.data.currently.temperature);
    socket.emit("FromAPI", res.data.currently.temperature);
  } catch (error) {
    console.error(`Error: ${error.code}`);
  }
};

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