Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist data using expressjs, reactjs?

I have created a simple chat app. I want to persist data so whenever I refresh it should show the previous chat also. Currently, I am using socket.io, reactjs and nodejs/express. When I refresh the page all chats are gone why so? I think my backend is not working in below code. Currently, only client side is working and not backend why so? What is wrong in server.js?

Code:

server.js:

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

const app = express();

server = app.listen(5000, function(){
  console.log('server is running on port 5000')
});

io = socket(server);

io.on('connection', (socket) => {
  console.log(socket.id);

  socket.on('SEND_MESSAGE', function(data){
      io.emit('RECEIVE_MESSAGE', data);
  })

});

chat.js:

import React, { Component } from 'react'
import './chat.css'
import Icon, {
    Ionicons,
} from 'react-web-vector-icons'
import io from "socket.io-client";

export default class Chat extends Component {

    constructor(props){
        super(props);

        this.state = {
            message: '',
            messages: []
        };

        this.socket = io('localhost:5000');

        this.socket.on('RECEIVE_MESSAGE', function(data){
            addMessage(data);
        });

        const addMessage = data => {
            console.log(data);
            this.setState({messages: [...this.state.messages, data]});
            console.log(this.state.messages);
        };

        this.sendMessage = ev => {
            ev.preventDefault();
            this.socket.emit('SEND_MESSAGE', {
                message: this.state.message
            })
            this.setState({message: ''});
        }

    }

    render() {
        return (
        <div>
                <div id="status"></div>
                <div id="chat">
                    <div className="card">
                        <div id="messages" className="card-block">
                            {this.state.messages.map(message => {
                                    return (
                                        <div className="msgCard">{message.message}</div>
                                    )
                            })}
                        </div>
                    </div>
                    <div className="row">
                        <div className="column">
                            <input id="inputmsg" type="text" placeholder="Enter Message...."
                            value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
                        </div>
                        <div className="column2">
                            <button id="send" className="button" onClick={this.sendMessage}>Send</button>
                        </div>
                    </div>
                </div>
        </div>
        )
    }
}

Note: backend is working on port 5000 and client on 3000 using concurrently. When I go to port 5000 I am getting error 404 why so?

Screenshot:

enter image description here

Chat app:

enter image description here

like image 348
fun joker Avatar asked Sep 22 '26 18:09

fun joker


1 Answers

You have to save somewhere you data. Yes it is possible without a database. Here I have implemented it using LocalStorage which resides in the browser.

this.state = {
        // Get previously saved messages.
        message: '',
        messages: JSON.parse(LocalStorage.getItem('messages')) || [],
    };


const addMessage = data => {
        console.log(data);
        this.setState({messages: [...this.state.messages, data]});
        console.log(this.state.messages);
        // Saving to HTML5 LocalStorage
        LocalStorage.setItem('messages' , JSON.stringify(this.state.messages);
    };

I hope it helps. Leave a comment if u face any issue.

like image 133
bereket gebredingle Avatar answered Sep 25 '26 07:09

bereket gebredingle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!