Create a Real-time Posting App with Socket.io in React.js and Node server. (Client Side Tutorial)
Tags: webdev, javascript, react, node
Published: 2022-12-16 02:09:49

**_Here is only react.js client side tutorial, you can find my react.js server side tutorial below._**
{% embed https://dev.to/luckey/create-a-real-time-posting-app-with-socketio-in-reactjs-and-node-server-server-side-tutorial-fn2 %}

## 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:
```javascript
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>
    </>
  )
}
```
The result will looks like below (styles may differ)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0mbmnr3kw45tihfkgy5.png)

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

```javascript
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('');
    };
```

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

```javascript
    // 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]);
    });
```

---

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ttecai1f6rskpsndsb1w.png)

> Let's try if our application is working!
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfl4qxbbmdkjbajv2zrl.gif)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yuog7yv5id08nd4yb73p.png)

> And get the response as expect:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uao3mhsjgf0u35c68j22.png)

> Meanwhile, our list of messages also got updated.

---

## Common Errors

> Your server side may not running

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70ayw3b555b8p3h0vagl.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wrckiqdff215bgxvj6v3.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60rhfbwi8h404k31o5gg.png)








---

## 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._**
{% embed https://dev.to/luckey/create-a-real-time-posting-app-with-socketio-in-reactjs-and-node-server-server-side-tutorial-fn2 %}