Issue
I connect DS18B20 to Raspberry Pi and I try to use NodeJS with React to display the temperature on the browser, I also use SocketIO to display realtime temperature because the temperature always changes.
I have temperature.js to get the temperature from file, this is ok.
I have app.js as the server with socketio, I try to call function but it show Promise { pending } , then I change to async/await, now I can get the temperature but on the client side is error.
app.js as below
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const port = 4001;
const index = require('./routes/index');
const getTemperature = require('./utils/temperature');
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIO(server);
let interval;
io.on("connection", (socket) => {
console.log("New client connected");
if(interval) {
clearInterval(interval);
}
interval = setInterval(() => getApiAndEmit(socket), 1000);
socket.on("disconnect", () => {
console.log("Client disconnected");
clearInterval(interval);
});
});
async function broadcast() {
var temp = await getTemperature();
return temp;
}
var temperature = broadcast();
const getApiAndEmit = socket => {
const response = temperature;
console.log(response);
socket.emit("FromAPI", response);
};
server.listen(port, () => console.log(`Listening on port ${port}`));
The error from the client side = "Objects are not valid as a React child (found: object with keys {})"
Below is the console.log result
Promise { 29.062 }
Promise { 29.062 }
Promise { 29.062 }
Promise { 29.062 }
How can I get the data from the Promise { data }???
Solution
Can try this:
broadcast().then(t => { console.log(t); });
Answered By - ta4h1r