,

All Users Fetched in Real Time | MERN Stack Project for Chat App

Posted by


In this tutorial, we will be building a real-time chat application using the MERN stack (MongoDB, Express, React, Node.js) and integrating a feature to fetch all users so that users can chat with each other in real-time.

Before we start, make sure you have Node.js and MongoDB installed on your local machine.

Step 1: Set up the Node.js backend

First, we need to set up our Node.js backend. Create a new directory for your project and run the following commands to initialize a new Node.js project and install the necessary dependencies:

mkdir real-time-chat-app
cd real-time-chat-app
npm init -y
npm install express mongoose socket.io

Next, create a new file named server.js and add the following code to set up our Express server and connect to the MongoDB database:

const express = require('express');
const mongoose = require('mongoose');
const app = express();

mongoose.connect('mongodb://localhost/real-time-chat-app', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

const server = app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Step 2: Set up the MongoDB database

Next, we need to set up our MongoDB database. You can either set up a local MongoDB instance or use a cloud-based solution like MongoDB Atlas. Create a new database named real-time-chat-app and define a User schema for storing user data.

const userSchema = new mongoose.Schema({
  username: String,
});

const User = mongoose.model('User', userSchema);

Step 3: Implement the logic to fetch all users

Now that we have set up our backend, we can implement the logic to fetch all users from the database. Create a new route in server.js to handle the API request to fetch all users:

app.get('/api/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

Step 4: Set up the React frontend

Create a new directory named client in your project directory and run the following commands to set up a new React project and install the necessary dependencies:

npx create-react-app client
cd client
npm install socket.io-client

Next, create a new file named Chat.js in the src/components directory of your React project and add the following code to fetch all users from the backend using the useEffect hook:

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const Chat = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('/api/users')
      .then((res) => res.json())
      .then((data) => setUsers(data));
  }, []);

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map((user) => (
          <li key={user._id}>{user.username}</li>
        ))}
      </ul>
    </div>
  );
};

export default Chat;

Step 5: Connect the React frontend to the backend using socket.io

To enable real-time chat functionality, we will use socket.io to establish a bidirectional communication channel between the frontend and backend. Modify the server.js file to set up the socket.io server and listen for connections:

const io = require('socket.io')(server);

io.on('connection', (socket) => {
  console.log('A user connected');
});

app.get('/api/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

Modify the Chat.js file in your React frontend to establish a connection to the socket.io server and emit a join event when the component mounts:

useEffect(() => {
  const socket = io('http://localhost:3000');

  socket.on('connect', () => {
    console.log('Connected to socket.io server');
    socket.emit('join', { username: 'JohnDoe' });
  });

  return () => {
    socket.disconnect();
  };
}, []);

That’s it! You have successfully set up a real-time chat application using the MERN stack with the ability to fetch all users. You can now extend the functionality by adding features like sending messages, creating rooms, and displaying online/offline status. Happy coding!

0 0 votes
Article Rating

Leave a Reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@aabhishakemishra
13 days ago

Please implement search and pagination things for production labels

@Monkey-king714
13 days ago

Best Tutor and Channel for Everyone.

@nelsonrivers8546
13 days ago

Why does this keep happening? I cannot download any video in any of your series whenever the video is stamped with "Members first". I am a paying customer. I am considering cancelling my subscription if this keeps happening. I reported this to you many times on other series in which you block a paying customer from downloading videos stamped with "Members first". Please fix this. You impact my ability to learn away from Youtube when I want to visit and study in locations that have no Wifi.

3
0
Would love your thoughts, please comment.x
()
x