fun joker
fun joker

Reputation: 1727

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

Upvotes: 3

Views: 2399

Answers (3)

pandamakes
pandamakes

Reputation: 591

To answer your second question first:

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 ?

Your node/express/socket-io backend is running on port 5000. Your dev-server for your react application (which serves HTML/JS/CSS files) is running on port 3000 (I'm assuming). Trying to connect to your node/express/socket-io backend with your browser (which tries to fetch files via HTTP protocol) results in a 404.

To persist older messages, as others have said, you need to use a db. either localStorage, which stores the data to PC, server side, you could use in memory storage (just push old message in an array, and replay when user connect), or actual db like mongo, sql, etc.

Upvotes: 1

bereket gebredingle
bereket gebredingle

Reputation: 13016

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.

Upvotes: 1

Kesavan R
Kesavan R

Reputation: 711

Your server code not storing chat data anywhere in any db. its now act like middleware receiving the message and sending message to client.

you are listening port 5000 but your not handling any incoming requests so its throwing error.

Upvotes: 1

Related Questions