How to build a real-time chat app with react node Socket IO and HarperDB

0 votes
Can someone help me with the code and example of how to build a real-time chat app with react node Socket.IO and HarperDB?
Mar 10 in Node-js by Nidhi
• 12,580 points
66 views

1 answer to this question.

0 votes

Set Up HarperDB:

Create a HarperDB instance (cloud or local).

Create a schema (e.g., chat_app) and a table (e.g., messages).

Backend (Node.js):

Initialize a Node.js project: npm init -y.

Install dependencies: npm install express socket.io harperdb.

Set up an Express server with Socket.IO for real-time communication.

Use HarperDB SDK to store and fetch messages.

const express = require("express");

const http = require("http");

const { Server } = require("socket.io");

const harperdb = require("harperdb");

const app = express();

const server = http.createServer(app);

const io = new Server(server);

const db = harperdb({

  host: "your-harperdb-url",

  username: "your-username",

  password: "your-password",

});

io.on("connection", (socket) => {

  console.log("A user connected");

  socket.on("sendMessage", async (message) => {

    await db.insert({

      table: "messages",

      records: [message],

    });

    io.emit("receiveMessage", message);

  });

  socket.on("disconnect", () => {

    console.log("User disconnected");

  });

});

server.listen(5000, () => console.log("Server running on port 5000"));

Frontend (React):

Create a React app: npx create-react-app chat-app.

Install Socket.IO client: npm install socket.io-client.

Connect to the backend and handle real-time messaging.

import React, { useEffect, useState } from "react";

import io from "socket.io-client";

const socket = io("http://localhost:5000");

function App() {

  const [message, setMessage] = useState("");

  const [messages, setMessages] = useState([]);

  useEffect(() => {

    socket.on("receiveMessage", (message) => {

      setMessages((prev) => [...prev, message]);

    });

  }, []);

  const sendMessage = () => {

    socket.emit("sendMessage", { text: message, user: "User" });

    setMessage("");

  };

  return (

    <div>

      <div>

        {messages.map((msg, i) => (

          <div key={i}>{msg.user}: {msg.text}</div>

        ))}

      </div>

      <input

        value={message}

        onChange={(e) => setMessage(e.target.value)}

      />

      <button onClick={sendMessage}>Send</button>

    </div>

  );

}

export default App;

Run the App:

Start the backend: node server.js.

Start the frontend: npm start.

answered Mar 10 by Tanvi

Related Questions In Node-js

0 votes
1 answer

How to build a product list app with redux-saga handling data fetching?

Example of Retry Logic with Redux-Saga Import Required ...READ MORE

answered Mar 19 in Node-js by Tanvi
44 views
0 votes
1 answer

How to programmatically send a 404 response with Express/Node?

Hello @kartik, The method is: res.sendStatus(404); Express will send a ...READ MORE

answered Jul 16, 2020 in Node-js by Niroj
• 82,840 points
3,695 views
0 votes
1 answer

How to update a value in a json file and save it through node.js?

//install ciql-json : npm i ciql-json const ciqlJson ...READ MORE

answered May 26, 2021 in Node-js by Sirus

edited Mar 5 26,204 views
0 votes
1 answer

How to “Ping” from a Node.js app?

Hello @kartik, You could use exec to call the system ...READ MORE

answered Oct 16, 2020 in Node-js by Niroj
• 82,840 points
4,885 views
0 votes
1 answer

How to Handle Blocking Threads in a Ruby Chat Server for Server Commands?

To handle blocking threads in a Ruby ...READ MORE

answered Mar 10 in Node-js by Tanvi
42 views
0 votes
1 answer

How to fix Service Unavailable error?

Steps to Fix "Service Unavailable" Error Check Server ...READ MORE

answered Mar 10 in Node-js by Tanvi
75 views
0 votes
1 answer

Why is my 503 site temporarily out of service?

Common Causes and Fixes Server Overload: High traffic or ...READ MORE

answered Mar 10 in Node-js by Tanvi
70 views
0 votes
1 answer
0 votes
1 answer

How to Build a Music Streaming App with React Native

1. Set Up Your Environment Install Node.js, npm/yarn, ...READ MORE

answered 7 hours ago in Node-js by anonymous
11 views
0 votes
1 answer

How to Handle Jest Unit Testing for 'ɵcmp' in a React-in-Angular Hybrid App?

Encountering the 'ɵcmp' property error during Jest ...READ MORE

answered Dec 23, 2024 in Node-js by Navya
104 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP