1

I have a challenge problem with my exercise while learning Socket via examples in Internet.

And here the link to the example I reference:

https://www.freecodecamp.org/news/build-a-realtime-chat-app-with-react-express-socketio-and-harperdb/#project-setup

I don't know how to keep my data through page reloads.

In the example above, That also have a solution mentioned. That's using the browser's localStorage. I also tried applying. But I don't know if I'm using it the wrong way. It seems that the application not only does not completely solve the problem, but also creates many other problems.

Here is code for server side:

const express = require('express');
const app = express();
const http = require('http');
const cors = require('cors');
const { Server } = require('socket.io');
const harperSaveMessage = require('./services/harper-save-message'); // Add this
const harperGetMessages = require('./services/harper-get-messages'); // Add this
const leaveRoom = require('./utils/leave-room'); // Add this

app.use(cors()); // Add cors middleware

const server = http.createServer(app);

// app.get('/', (req, res) => {
//     res.send('hello world!');
// })

// Add this
// Create an io server and allow for CORS from http://localhost:3000 with GET and POST methods
const io = new Server(server, { 
    cors: {
        origin: 'http://localhost:3000',
        methods: ['GET', 'POST'],
    }
});

const CHAT_BOT = 'ChatBot';
let chatRoom = ''; // E.g. javascript, node,...
let allUsers = []; // All users in current chat room

// Add this
// Listen for when the client connects via socket.io-client
io.on('connection', (socket) => {
    console.log(`User connected ${socket.id}`);

    // Other code...    

    // Add this
    socket.on('disconnect', () => {
        console.log('User disconnected from the chat');
        const user = allUsers.find((user) => user.id == socket.id);
        const __createdtime__ = Date.now();

        if (user?.username) {
            allUsers = leaveRoom(socket.id, allUsers);
            socket.to(chatRoom).emit('chatroom_users', allUsers);
            socket.to(chatRoom).emit('receive_message', {
                username: CHAT_BOT,
                message: `${user.username} has disconnect from the chat.`,
                __createdtime__,
            });
            console.log(`${user.username} disconnected from the chat`);
        }

    });

    
});

server.listen(4000, () => 'Server is running on port 4000');

In this example using React for front-end. It has some component like:

Go more specifically into the Messages component and RoomAndUsers component message.js:

Except for the socket which is taken from io.connect("http://localhost:4000"), all props use useState to store the value.

For detail, here is the link to my code in github: https://github.com/edohajime/REALTIME-CHAT-APP-WITH-ROOMS

Can anyone else hint some way to pass this problem?

Thanks!

Before that I tried adding 2 useEffect to sync each localStorage variable on client side browser.

In this respect messages seem to work on page reload but not with room chat user. When reloading the page, it not only failed to get data from localStorage, but also lost the current user.

Hajime
  • 21
  • 3
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Jul 21 '23 at 04:22

0 Answers0