DEV Community

Luckey
Luckey

Posted on

Create a Real-time Posting App with Socket.io in React.js and Node server. (Client Side Tutorial)

Here is only react.js client side tutorial, you can find my react.js server side tutorial below.

Introduction

  • Why we need real-time posting?

Real-time posting refers to the ability for users to post and view new content on a website without the need for manual refreshing. This is made possible by using web technologies such as websockets, which allow the server and client to communicate in real-time.

  • How other projects real-time posting can do?

Real-time posting is useful in many different types of web applications. For example, it can be used in chat applications to instantly send and receive messages, in social media applications to display new posts and updates in real-time, and in online collaboration tools to share and edit documents in real-time.


Build a simple React.js Component

Code:

export const MailchimpForm = () => {
    // Initialize the state for the message input and list of messages
    const [message, setMessage] = useState('');
    // Add some default to the list of messages
    const [messages, setMessages] = useState([
        'Welcome to the real-time Post Application!',
        'This is a test Post',
        'This is another test Post'
    ]);

return (
    <>
        <h1>Real-time Post Application</h1>
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
            />
            <button type="submit">Send</button>
        </form>
        <ul>
            {messages.map((msg, index) => (
                <li key={index}>{msg}</li>
            ))}
        </ul>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

The result will looks like below (styles may differ)
Image description

Let's create the handleSubmit function to submit new post to our server using API.

const handleSubmit = async (e) => {
    // Prevent the form from refreshing the page
    e.preventDefault();

    // Call the API with try-catch to avoid potential error
    try {
        let response = await fetch("http://localhost:8000/post", {
            method: "POST",
            headers: {
                "Content-Type":
"application/json;charset=utf-8",
            },
            body: JSON.stringify({ post: message }),
        });
        let result = await response.json();
    } catch (e) {
        console.log(e);
    }

        setMessage('');
    };
Enter fullscreen mode Exit fullscreen mode

Now we can set up socket.io configure to receive newPost data through websocket from server side.

    // Initialize the socket.io client and connect to the server
    const socket = io("http://your-server-url:socket-port");

    // Set up an event listener to receive new messages from the server
    socket.on('new_post', (msg) => {
        // Add the new message to the list of messages
        setMessages([...messages, msg]);
    });
Enter fullscreen mode Exit fullscreen mode

Testing real-time posting application

As our server side and client side both on, we can see the log when a connection is built from clients like below:

Image description

Let's try if our application is working!
Image description

We can check how API is called from developer tools
we send the request as below:

Image description

And get the response as expect:

Image description

Meanwhile, our list of messages also got updated.


Common Errors

Your server side may not running

Image description

Your cors policy origin URL in server side is not the same as your client side URL. (Check your client running port)

Image description

Your socket server URL in client side is not the same as your server side URL. (Check your server running port)

Image description


Conclusion

In conclusion, real-time posting enhances the user experience by making the web app feel more interactive and responsive. It also allows for more efficient communication and collaboration among users.

Here is only react.js client side tutorial, you can find my react.js server side tutorial below.

Top comments (0)