Creating an upvote system with React and Socket.io 🥳 🔝
Tags: webdev, javascript, tutorial, node
Published: 2022-12-05 15:24:04

## What is this article about?
Upvotes became a great way to understand what your visitors want. You can take websites like [ProductHunt](https://producthunt.com), and public roadmaps like [Gleap](https://roadmap.gleap.io/), [Upvoty](https://feedback.yourappdomain.com), [Prodcamp](https://roadmap.prodcamp.com), have the ability to let user share their thoughts (in votes).
Even [Reddit](https://reddit.com), one of the most popular social media lets people upvote or downvote your posts. **We are going to build something similar with images!**

![Upvote](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nm8hpw74rfdo9gf5l4s1.png)

In this article, you'll learn how to create an upvoting application that allows users to upload images using Websockets and upvote their favorite photos. You'll also learn how to send emails via EmailJS to notify users when their images gain a vote.

![Transformers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrnfed3z4ep2ooxb07bo.gif)

## Why Socket.io (Websockets)?
Websockets allows us to use bi-directional communication with the server. It means that if we put in an upvote, we can inform the other user about the new upvote without refreshing the page or using [long-polling](https://www.educative.io/answers/what-is-http-long-polling).

Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between software applications and a Node.js server. It is optimised to process a large volume of data with minimal delay and provides better functionalities, such as fallback to HTTP long-polling or automatic reconnection.

## Novu - the first open-source notification infrastructure
Just a quick background about us. Novu is the first open-source [notification infrastructure](https://novu.co). We basically help to manage all the product notifications. It can be **In-App** (the bell icon like you have in Facebook - **Websockets**), Emails, SMSs and so on.

![Novu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yn90yvsd87tgik03c08v.gif)

I would be super happy if you could give us a star! And let me also know in the comments ❤️
https://github.com/novuhq/novu

## How to create a real-time connection with React and Socket.io

Here we'll set up the project environment for the image upvoting application. You will also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.

Create the project folder containing two sub-folders named client and server.

```bash
mkdir upvote-app
cd upvote-app
mkdir client server
```

Navigate into the client folder via your terminal and create a new React.js project.

```bash
cd client
npx create-react-app ./
```

Install Socket.io client API, React Toastify, and React Router. [React Router](https://reactrouter.com/en/6.4.4) is a JavaScript library that enables us to navigate between pages in a React application, and [React Toastify](https://www.npmjs.com/package/react-toastify) is used to display colourful notifications to the users.

```bash
npm install socket.io-client react-router-dom react-toastify
```

Delete the redundant files such as the logo and the test files from the React app, and update the App.js file to display `Hello World` as below.

```jsx
function App() {
    return (
        <div>
            <p>Hello World!</p>
        </div>
    );
}
export default App;
```

Add the Socket.io client API to the React app as below:

```jsx
import { io } from "socket.io-client";

//👇🏻 http://localhost:4000 is where the server host URL.
const socket = io.connect("http://localhost:4000");

function App() {
    return (
        <div>
            <p>Hello World!</p>
        </div>
    );
}
export default App;
```

Navigate into the server folder and create a `package.json` file.

```bash
cd server & npm init -y
```

Install Express.js, CORS, Nodemon, and Socket.io Server API.

```bash
npm install express cors nodemon socket.io react-icons
```

[Express.js](https://expressjs.com/) is a fast, minimalist framework that provides several features for building web applications in Node.js. [CORS](https://www.npmjs.com/package/cors) is a Node.js package that allows communication between different domains.

[Nodemon](https://www.npmjs.com/package/nodemon) is a Node.js tool that automatically restarts the server after detecting file changes, and [Socket.io](https://socket.io/docs/v4/server-api) allows us to configure a real-time connection on the server.

Create an index.js file - the entry point to the web server.

```bash
touch index.js
```

Set up a Node.js server using Express.js. The code snippet below returns a JSON object when you visit the `http://localhost:4000/api` in your browser.

```jsx
//👇🏻index.js
const express = require("express");
const app = express();
const PORT = 4000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});
```

Import the HTTP and the CORS library to allow data transfer between the client and the server domains.

```jsx
const express = require("express");
const app = express();
const PORT = 4000;

//👇🏻 New imports
const http = require("http").Server(app);
const cors = require("cors");

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

http.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});
```

Next, add Socket.io to the project to create a real-time connection. Before the `app.get()` block, copy the code below.

```jsx
//👇🏻 New imports
.....
const socketIO = require('socket.io')(http, {
    cors: {
        origin: "http://localhost:3000"
    }
});

//👇🏻 Add this before the app.get() block
socketIO.on('connection', (socket) => {
    console.log(`⚡: ${socket.id} user just connected!`);

    socket.on('disconnect', () => {
      socket.disconnect()
      console.log('🔥: A user disconnected');
    });
});
```

From the code snippet above, the `socket.io("connection")` function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.

When you refresh or close the web page, the socket fires the disconnect event showing that a user has disconnected from the socket.

Configure Nodemon by adding the start command to the list of scripts in the `package.json` file. The code snippet below starts the server using Nodemon.

```jsx
//👇🏻 In server/package.json"
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
}
```

You can now run the server with Nodemon by using the command below.

```bash
npm start
```

## Building the user interface

Here, we'll create the user interface for the upvoting application to enable users to sign in, upload images, and upvote any picture of their choice.
There are two rules required when building the upvoting application:

- users can only vote once.
- users can not upvote their own images.

Later in the tutorial, I will guide you on how you can build such a efficient upvoting system.

Navigate into the `client/src` folder and create a components folder containing the `Login.js`, `Register.js`, `Photos.js`, `UploadPhoto.js`, `MyPhotos`, and `SharePhoto.js` files.

```bash
cd client
mkdir components
cd components
touch Login.js Register.js Photos.js UploadPhoto.js MyPhoto.js SharePhoto.js
```

From the code snippet above:

- The `Login` component is the application's home page. It prompts users to sign in to the application.
- The `Register` component enables new users to create an account before they can sign in to the application.
- The `Photos` component is the home page displayed to the users after authentication. Users can view all the available images on this page and upvote them.
- The `UploadPhoto` is only visible to authenticated users and allows users to upload images to the list of photos on the web application.
- The `MyPhoto` page allows users to view only their uploaded images and share their profile links with friends.
- The `SharePhoto` component is a dynamic route that shows all the images uploaded by a user.

Update the `App.js` file to render the newly created components on different routes via React Router as below:

```jsx
import React from "react";
//👇🏻 React Router configuration & routes
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Photos from "./components/Photos";
import Login from "./components/Login";
import Register from "./components/Register";
import UploadPhoto from "./components/UploadPhoto";
import MyPhotos from "./components/MyPhotos";
import SharePhoto from "./components/SharePhoto";
//👇🏻 React Toastify configuration
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
//👇🏻 Websockets configuration
import { io } from "socket.io-client";

const App = () => {
	const socket = io.connect("http://localhost:4000");

	return (
		<>
			<BrowserRouter>
				<Routes>
					<Route path='/' element={<Login socket={socket} />} />
					<Route path='/register' element={<Register socket={socket} />} />
					<Route path='/photos' element={<Photos socket={socket} />} />
					<Route
						path='/photo/upload'
						element={<UploadPhoto socket={socket} />}
					/>
					<Route path='/user/photos' element={<MyPhotos socket={socket} />} />
					<Route path='/share/:user' element={<SharePhoto socket={socket} />} />
				</Routes>
			</BrowserRouter>
			<ToastContainer />
		</>
	);
};

export default App;
```

Navigate into the `src/index.css` file and copy the code below. It contains all the CSS required for styling this project.

```css
@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
* {
	margin: 0;
	box-sizing: border-box;
	font-family: "Space Grotesk", sans-serif;
	color: #2b3a55;
}
body {
	padding: 0;
	margin: 0;
}
button {
	border: none;
	outline: none;
	cursor: pointer;
}
input {
	padding: 10px 15px;
}
.navbar {
	width: 100%;
	min-height: 10vh;
	padding: 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background-color: #f2e5e5;
	position: sticky;
	top: 0;
	z-index: 10;
}
.nav__BtnGroup a,
.nav__BtnGroup button {
	padding: 15px;
	width: 200px;
	font-size: 16px;
	cursor: pointer;
	outline: none;
	background-color: #fff;
	border: none;
	border-radius: 3px;
	text-decoration: none;
}
.nav__BtnGroup a {
	margin-right: 10px;
}
.nav__BtnGroup a:hover,
.nav__BtnGroup button:hover {
	background-color: #ce7777;
	color: #fff;
}
.login,
.register {
	width: 100%;
	min-height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
}
.login__form,
.register__form {
	width: 500px;
	display: flex;
	flex-direction: column;
}
.input {
	padding: 12px 10px;
	margin-bottom: 20px;
	border-radius: 4px;
	border: 1px solid #e8c4c4;
}
.loginBtn,
.registerBtn {
	padding: 15px;
	font-size: 16px;
	cursor: pointer;
	background-color: #f2e5e5;
	color: #2b3a55;
	border: none;
	outline: none;
	border-radius: 5px;
	margin-bottom: 20px;
}
.loginBtn:hover,
.registerBtn:hover {
	background-color: #ce7777;
	color: #fff;
}
.link {
	color: #ce7777;
	cursor: pointer;
	text-decoration: none;
}
.photoContainer {
	width: 100%;
	min-height: 90vh;
	padding: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-wrap: wrap;
}
.photoContainer > * {
	margin: 15px;
}
.photo {
	width: 300px;
	height: 350px;
	position: relative;
	border-radius: 10px;
	box-shadow: 0 2px 8px 0 rgba(99, 99, 99, 0.2);
}
.imageContainer {
	width: 100%;
	position: relative;
	height: 100%;
}
.photo__image {
	width: 100%;
	height: 100%;
	position: absolute;
	object-fit: cover;
	border-radius: 10px;
}
.upvoteIcon {
	background-color: #fff;
	padding: 10px 20px;
	position: absolute;
	bottom: 5px;
	right: 5px;
	cursor: pointer;
	border-radius: 5px;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.upvoteIcon:hover {
	background-color: #f2e5e5;
}

.uploadContainer {
	width: 100%;
	min-height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
}
.uploadText {
	width: 80%;
}
.uploadText form {
	display: flex;
	flex-direction: column;
}

.uploadText > h2 {
	margin-bottom: 20px;
}
.uploadBtn {
	margin-top: 20px;
	padding: 10px;
	background-color: #ce7777;
	color: #fff;
}
.copyDiv {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}
.copyContainer {
	margin-top: 20px;
	padding: 15px;
	cursor: pointer;
	background-color: #ce7777;
	border-radius: 5px;
}
```

### The Login page

Copy the code below into the `Login` component. The application accepts the username and password from the user.

```jsx
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";

const Login = ({ socket }) => {
	const navigate = useNavigate();
	const [username, setUsername] = useState("");
	const [password, setPassword] = useState("");

	const handleSignIn = (e) => {
		if (username.trim() && password.trim()) {
			e.preventDefault();
			console.log({ username, password });
			setPassword("");
			setUsername("");
		}
	};
	return (
		<div className='login'>
			<h2 style={{ marginBottom: "30px" }}>Login</h2>
			<form className='login__form' method='POST' onSubmit={handleSignIn}>
				<label htmlFor='username'>Username</label>
				<input
					type='text'
					className='input'
					name='username'
					id='username'
					required
					value={username}
					onChange={(e) => setUsername(e.target.value)}
				/>
				<label htmlFor='password'>Password</label>
				<input
					type='password'
					className='input'
					name='password'
					id='password'
					required
					minLength={6}
					value={password}
					onChange={(e) => setPassword(e.target.value)}
				/>
				<button className='loginBtn'>LOG IN</button>
				<p style={{ textAlign: "center" }}>
					Don't have an account?{" "}
					<Link className='link' to='/register'>
						Create one
					</Link>
				</p>
			</form>
		</div>
	);
};

export default Login;
```

![Register Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ns1i06dpyl423th44zp.png)

### The Register page

Copy the code below into the `Register.js` file to accepts the user's email, username and password.

```jsx
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";

const Register = ({ socket }) => {
	const navigate = useNavigate();
	const [username, setUsername] = useState("");
	const [password, setPassword] = useState("");
	const [email, setEmail] = useState("");

	const handleRegister = (e) => {
		e.preventDefault();
		if (username.trim() && password.trim() && email.trim()) {
			console.log({ username, email, password });
			setPassword("");
			setUsername("");
			setEmail("");
		}
	};
	return (
		<div className='register'>
			<h2 style={{ marginBottom: "30px" }}>Register</h2>
			<form className='register__form' method='POST' onSubmit={handleRegister}>
				<label htmlFor='email'>Email Address</label>
				<input
					type='email'
					className='input'
					name='email'
					id='email'
					required
					value={email}
					onChange={(e) => setEmail(e.target.value)}
				/>

				<label htmlFor='username'>Username</label>
				<input
					type='text'
					className='input'
					name='username'
					id='username'
					required
					value={username}
					onChange={(e) => setUsername(e.target.value)}
				/>

				<label htmlFor='password'>Password</label>
				<input
					type='password'
					className='input'
					name='password'
					id='password'
					required
					minLength={6}
					value={password}
					onChange={(e) => setPassword(e.target.value)}
				/>
				<button className='registerBtn'>REGISTER</button>
				<p style={{ textAlign: "center" }}>
					Already have an account?{" "}
					<Link className='link' to='/'>
						Sign in
					</Link>
				</p>
			</form>
		</div>
	);
};

export default Register;
```

![Register Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ensp7iz52fvjqmhnvcz3.png)

### The Photos component

This component is divided into two sub-components which are the navigation and the main container containing the available images.

![Photo Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tn4n45wfpspndae4pbnk.png)

Copy the code below into the `Photos.js` file.

```jsx
import React, { useEffect, useState } from "react";
import Nav from "./Nav";
import PhotoContainer from "./PhotoContainer";

const Home = ({ socket }) => {
	const [photos, setPhotos] = useState([
		{
			id: "1",
			image_url:
				"https://raw.githubusercontent.com/novuhq/blog/main/upvote-app-with-react-and-nodejs/server/images/dog1.jpg",
			vote_count: 0,
		},
		{
			id: "2",
			image_url:
				"https://raw.githubusercontent.com/novuhq/blog/main/upvote-app-with-react-and-nodejs/server/images/dog2.jpg",
			vote_count: 0,
		},
	]);

	return (
		<div>
			<Nav />
			<PhotoContainer photos={photos} socket={socket} />
		</div>
	);
};

export default Home;
```

Create the Nav and PhotoContainer sub-components.

```bash
touch Nav.js PhotoContainer.js
```

Copy the code below into the `Nav.js` file.

```jsx
import React from "react";
import { Link } from "react-router-dom";

const Nav = () => {
    return (
        <nav className='navbar'>
            <h3>PhotoShare</h3>
            <div className='nav__BtnGroup'>
                <Link to='/user/photos' style={{ marginRight: "10px" }}>
                    My Photos
                </Link>
                <Link to='/photo/upload'>Upload Photo</Link>
            </div>
        </nav>
    );
};

export default Nav;
```

Update the `PhotoContainer.js` file as below:

```jsx
import React, { useEffect } from "react";
import { MdOutlineArrowUpward } from "react-icons/md";

const PhotoContainer = ({ photos, socket }) => {
	const handleUpvote = (id) => {
		console.log("Upvote", id);
	};

	return (
		<main className='photoContainer'>
			{photos.map((photo) => (
				<div className='photo' key={photo.id}>
					<div className='imageContainer'>
						<img
							src={photo.image_url}
							alt={photo.id}
							className='photo__image'
						/>
					</div>

					<button className='upvoteIcon' onClick={() => handleUpvote(photo.id)}>
						<MdOutlineArrowUpward
							style={{ fontSize: "20px", marginBottom: "5px" }}
						/>
						<p style={{ fontSize: "12px", color: "#ce7777" }}>
							{photo.vote_count}
						</p>
					</button>
				</div>
			))}
		</main>
	);
};

export default PhotoContainer;
```

### The UploadPhoto component

Update the `UploadPhoto.js` to contain the code below:

```jsx
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";

const UploadPhoto = ({ socket }) => {
	const navigate = useNavigate();
	const [photoURL, setPhotoURL] = useState("");

	const handleSubmit = (e) => {
		e.preventDefault();
		console.log(photoURL);
	};

	return (
		<main className='uploadContainer'>
			<div className='uploadText'>
				<h2>Upload Image</h2>
				<form method='POST' onSubmit={handleSubmit}>
					<label>Paste the image URL</label>
					<input
						type='text'
						name='fileImage'
						value={photoURL}
						onChange={(e) => setPhotoURL(e.target.value)}
					/>
					<button className='uploadBtn'>UPLOAD</button>
				</form>
			</div>
		</main>
	);
};

export default UploadPhoto;
```

![MyPhotos component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvseyvqoe9cpg1c4yw2b.png)

### The MyPhotos component

Here, you'll learn how to copy and paste content with a click of a button using the [React-copy-to-clipboard](https://www.npmjs.com/package/react-copy-to-clipboard) library. Within the `MyPhotos` component, users can copy their profile URLs and share them with others.

> [React-copy-to-clipboard](https://www.npmjs.com/package/react-copy-to-clipboard) is a package that allows us to copy and paste contents via a button click in React.


![Copy to Clipboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kkkv9oxjw54x8h92165v.png)

Install the [React-copy-to-clipboard](https://www.npmjs.com/package/react-copy-to-clipboard) library by running the code below.

```jsx
npm install react-copy-to-clipboard
```

Copy the code below into the `MyPhotos.js` file.

```jsx
import React, { useEffect, useState } from "react";
//👇🏻 React Router configs
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import PhotoContainer from "./PhotoContainer";
//👇🏻 React-copy-to-clipboard config
import { CopyToClipboard } from "react-copy-to-clipboard";

const MyPhotos = ({ socket }) => {
	const navigate = useNavigate();
	const [photos, setPhotos] = useState([]);
	const [userLink, setUserLink] = useState("");

	//👇🏻 navigates users to the homepage (for now)
	const handleSignOut = () => {
		localStorage.removeItem("_id");
		localStorage.removeItem("_myEmail");
		navigate("/");
	};

	//👇🏻 This function runs immediately the content is copied
	const copyToClipBoard = () => alert(`Copied ✅`);

	return (
		<div>
			<nav className='navbar'>
				<h3>PhotoShare</h3>

				<div className='nav__BtnGroup'>
					<Link to='/photo/upload'>Upload Photo</Link>
					<button onClick={handleSignOut}>Sign out</button>
				</div>
			</nav>

			<div className='copyDiv'>
				<CopyToClipboard
					text={userLink}
					onCopy={copyToClipBoard}
					className='copyContainer'
				>
					<span className='shareLink'>Copy your share link</span>
				</CopyToClipboard>
			</div>

			<PhotoContainer socket={socket} photos={photos} />
		</div>
	);
};

export default MyPhotos;
```

From the code snippet above, `CopyToClipboard` is a component provided by [React-copy-to-clipboard](https://www.npmjs.com/package/react-copy-to-clipboard) that accepts two props: `text`- the content and the function that runs after copying the content - `onCopy`.

The code snippet above represents the page layout. We'll create the functionality in the subsequent sections.

### The SharePhoto component

Copy the code below into the `SharePhoto.js` file.

```jsx
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Nav from "./Nav";
import PhotoContainer from "./PhotoContainer";

const SharePhoto = ({ socket }) => {
	const navigate = useNavigate();
	const [photos, setPhotos] = useState([]);
	//👇🏻 This accepts the username from the URL (/share/:user)
	const { user } = useParams();

	return (
		<div>
			<Nav />
			<PhotoContainer socket={socket} photos={photos} />
		</div>
	);
};

export default SharePhoto;
```

Congratulations!🥂 You've completed the user interface for the upvoting application.
For the remaining part of this article, you'll learn how to send data between the React.js application and the Node.js server.

## How to create an authentication flow with Socket.io

Here, I'll guide you through creating an authentication flow via Socket.io. A user can create an account, and log in and out of the application.

### The user registration workflow

Update the `handleRegister` function within the `Register.js` component to send the user's email, username, and password to the server.

```jsx
const handleRegister = (e) => {
	e.preventDefault();
	if (username.trim() && password.trim() && email.trim()) {
		//👇🏻 triggers a register event
		socket.emit("register", { username, email, password });
		setPassword("");
		setUsername("");
		setEmail("");
	}
};
```

Listen to the event on server as done below:

```jsx
socketIO.on("connection", (socket) => {
	console.log(`⚡: ${socket.id} user just connected!`);

	//👇🏻 Create a listener to the event
	socket.on("register", (data) => {
		/*
		👇🏻 data will be an object containing the data sent from the React app
		*/
		console.log(data);
	});
	socket.on("disconnect", () => {
		socket.disconnect();
		console.log("🔥: A user disconnected");
	});
});
```

We've successfully retrieved the data sent from the React app on the server. Next, let's save the users' details.
First, create an empty array to hold all the user details and a function that generates a random string as ID.

```jsx
//👇🏻 outside the socket.io block
const database = [];
const generateID = () => Math.random().toString(36).substring(2, 10);
```

Update the event listener to save the user’s details.

```jsx
const database = [];
const generateID = () => Math.random().toString(36).substring(2, 10);

socket.on("register", (data) => {
	//👇🏻 Destructure the user details from the object
	const { username, email, password } = data;

	//👇🏻 Filters the database (array) to check if there is no existing user with the same email or username
	let result = database.filter(
		(user) => user.email === email || user.username === username
	);
	//👇🏻 If none, saves the data to the array. (the empty images array is required for the image uploads)
	if (result.length === 0) {
		database.push({
			id: generateID(),
			username,
			password,
			email,
			images: [],
		});
		//👇🏻 returns an event stating that the registration was successful
		return socket.emit("registerSuccess", "Account created successfully!");
	}
	//👇🏻 This runs only when there is an error/the user already exists
	socket.emit("registerError", "User already exists");
});
```

Next, listen to the two events likely to be triggered when a user registers on the web application.

```jsx
//👇🏻 Import toast from React Toastify
import { toast } from "react-toastify";

//👇🏻 Add a useEffect hook that listens to both both events
useEffect(() => {
	socket.on("registerSuccess", (data) => {
		toast.success(data);
		//👇🏻 navigates to the login page
		navigate("/");
	});
	socket.on("registerError", (error) => {
		toast.error(error);
	});
}, [socket, navigate]);
```

### The Login workflow

Update the `handleSignIn` function within the `Login.js` component to send the username and password of the user to the backend server.

```jsx
const handleSignIn = (e) => {
	if (username.trim() && password.trim()) {
		e.preventDefault();
		//👇🏻 triggers a login event
		socket.emit("login", { username, password });
		setPassword("");
		setUsername("");
	}
};
```

Create a listener to the event on the server.

```jsx
socketIO.on("connection", (socket) => {
	//...other functions

	socket.on("login", (data) => {
		//👇🏻 data - contains the username and password
		console.log(data)
	})
}
```

Update the event listener to log the user into the web application as below:

```jsx
socket.on("login", (data) => {
	//👇🏻 Destructures the credentials from the object
	const { username, password } = data;
	
	//👇🏻 Filters the array for existing objects with the same email and password
	
	let result = database.filter(
		(user) => user.username === username && user.password === password
	);
	//👇🏻 If there is none, it returns this error message
	if (result.length !== 1) {
		return socket.emit("loginError", "Incorrect credentials");
	}
	//👇🏻 Returns the user's email & id if the user exists
	socket.emit("loginSuccess", {
		message: "Login successfully",
		data: {
			_id: result[0].id,
			_email: result[0].email,
		},
	});
});
```

Listen to the two likely events within the `Login.js` file.

```jsx
useEffect(() => {
	socket.on("loginSuccess", (data) => {
		toast.success(data.message);
		//👇🏻 Saves the user's id and email to local storage for easy identification & for making authorized requests
		localStorage.setItem("_id", data.data._id);
		localStorage.setItem("_myEmail", data.data._email);
		//👇🏻 Redirects the user to the Photos component
		navigate("/photos");
	});
	//👇🏻 Notifies the user of the error message
	socket.on("loginError", (error) => {
		toast.error(error);
	});
}, [socket, navigate]);
```

Congratulations! We've created the authentication flow for the application.
Lastly, let's protect the remaining routes by allowing only authenticated users to view the pages. Copy the code snippet below into the `UploadPhoto`, `MyPhotos`, `SharePhoto`, and `Photos` components.

```jsx
useEffect(() => {
	function authenticateUser() {
		const id = localStorage.getItem("_id");
		/*
		👇🏻 If ID is false, redirects the user to the login page
		*/
		if (!id) {
			navigate("/");
		}
	}
	authenticateUser();
}, [navigate]);
```

## Adding and displaying images with Socket.io

In this section, you'll learn how to upload images to the server and display them within the React application via Socket.io.

### Uploading images to the server via Socket.io

Navigate into the `UploadPhoto` component and update the `handleSubmit` function as below:

```jsx
const handleSubmit = (e) => {
	e.preventDefault();
	//👇🏻 Gets the id and email from the local storage
	const id = localStorage.getItem("_id");
	const email = localStorage.getItem("_myEmail");
	/*
	👇🏻 triggers an event to the server 
	containing the user's credentials and the image url 
	*/
	socket.emit("uploadPhoto", { id, email, photoURL });
};
```

Create the event listener on the server that adds the image to the database.

```jsx
socket.on("uploadPhoto", (data) => {
	//👇🏻 Gets the id, email, and image URL
	const { id, email, photoURL } = data;
	//👇🏻 Search the database for the user
	let result = database.filter((user) => user.id === id);
	//👇🏻 creates the data structure for the image
	const newImage = {
		id: generateID(),
		image_url: photoURL,
		vote_count: 0,
		votedUsers: [],
		_ref: email,
	};
	//👇🏻 adds the new image to the images array
	result[0]?.images.unshift(newImage);
	//👇🏻 sends a new event containing the server response
	socket.emit("uploadPhotoMessage", "Upload Successful!");
});
```

Listen for the server's response within the React application.

```jsx
useEffect(() => {
	socket.on("uploadPhotoMessage", (data) => {
		//👇🏻 Displays the server's response
		toast.success(data);
		navigate("/photos");
	});
}, [socket, navigate]);
```

### Displaying the images within the React application

Here, we'll update the `Photos`, `MyPhotos`, and `SharePhoto` components to display the images.

- The `Photos` component displays all the available photos within the application.
- The `MyPhotos` component displays only the images uploaded by the user.
- The `SharePhoto` component displays the images uploaded by a user via its username.

**The Photos component**

Add a useEffect hook within the `Photos.js` file that retrieves all the images from the server when the component mounts.

```jsx
useEffect(() => {
	//👇🏻 search can be anything
	socket.emit("allPhotos", "search");
}, [socket]);
```

Listen to the event and return all the available images on the server.

```jsx
socket.on("allPhotos", (data) => {
	//👇🏻 an array to contain all the images
	let images = [];
	//👇🏻 loop through the items in the database
	for (let i = 0; i < database.length; i++) {
		//👇🏻 collect the images into the array
		images = images.concat(database[i]?.images);
	}
	//👇🏻 sends all the images through another event
	socket.emit("allPhotosMessage", {
		message: "Photos retrieved successfully",
		photos: images,
	});
});
```

Update the useEffect hook within the `Photos` component to retrieve the images as below:

```jsx
useEffect(() => {
	socket.emit("allPhotos", "search");
	//👇🏻 retrieve all the images from the server
	socket.on("allPhotosMessage", (data) => {
		setPhotos(data.photos);
	});
}, [socket]);
```

**The MyPhotos component**

Update the useEffect hook within the `MyPhotos` component to trigger an event that sends the user's id to the server via Socket.io.

```jsx
useEffect(() => {
	function authenticateUser() {
		const id = localStorage.getItem("_id");
		if (!id) {
			navigate("/");
		} else {
			//👇🏻 sends the user id to the server
			socket.emit("getMyPhotos", id);
		}
	}
	authenticateUser();
}, [navigate, socket]);
```

Listen to the event on the server and return the user's images.

```jsx
socket.on("getMyPhotos", (id) => {
	//👇🏻 Filter the database items
	let result = database.filter((db) => db.id === id);
	//👇🏻 Returns the images and the username
	socket.emit("getMyPhotosMessage", {
		data: result[0]?.images,
		username: result[0]?.username,
	});
});
```

Retrieve the images and username from the server as done below:

```jsx
useEffect(() => {
	socket.on("getMyPhotosMessage", (data) => {
		//👇🏻 sets the user's images
		setPhotos(data.data);
		//👇🏻 sets the user's profile link
		setUserLink(`http://localhost:3000/share/${data.username}`);
	});
}, [socket]);
```

**The SharePhoto component**

Update the `useEffect` hook within the `SharePhoto` component to request for the user's images when the component mounts.

```jsx
useEffect(() => {
	function authenticateUser() {
		const id = localStorage.getItem("_id");
		if (!id) {
			navigate("/");
		} else {
			//👇🏻 user - is the username from the profile link
			socket.emit("sharePhoto", user);
		}
	}
	authenticateUser();
}, [socket, navigate, user]);
```

Listen to the event on the server and return the user's images.

```jsx
socket.on("sharePhoto", (name) => {
	//👇🏻 Filters the database via the username
	let result = database.filter((db) => db.username === name);
	//👇🏻 Returns the images via another event
	socket.emit("sharePhotoMessage", result[0]?.images);
});
```

Retrieve the images from the server as below:

```jsx
useEffect(() => {
	socket.on("sharePhotoMessage", (data) => setPhotos(data));
}, [socket]);
```

Congratulations on making it thus far! 😊 You've learnt how to manipulate the data within the database and retrieve the items for each route. In the upcoming section, I'll guide you through how to upvote the images.

## How to upvote the images

Here, I will guide you through upvoting the images within the web application. Recall that users can not upvote their photos and can only upvote once.

Update the `handleUpvote` function within the `PhotoContainer.js` to send the user and the image ID to the server.

```jsx
const handleUpvote = (id) => {
	socket.emit("photoUpvote", {
		userID: localStorage.getItem("_id"),
		photoID: id,
	});
};
```

Listen to the event on the server and upvote the selected image via its ID.

```jsx
socket.on("photoUpvote", (data) => 
	const { userID, photoID } = data;
	let images = [];
	//👇🏻 saves all the images not belonging to the user into the images array
	for (let i = 0; i < database.length; i++) {
		//👇🏻 ensures that only other users' images are separated into the images array
		if (!(database[i].id === userID)) {
			images = images.concat(database[i]?.images);
		}
	}
	//👇🏻 Filter the images array for the image selected for upvote
	const item = images.filter((image) => image.id === photoID);
	/*
	👇🏻 Returns this error if the selected image doesn't belong to other users
	*/
	if (item.length < 1) {
		return socket.emit("upvoteError", {
			error_message: "You cannot upvote your photos",
		});
	}
	//👇🏻 Gets the list of voted users from the selected image
	const voters = item[0]?.votedUsers;
	//👇🏻 Checks if the user has not upvoted the image before
	const authenticateUpvote = voters.filter((voter) => voter === userID);
	//👇🏻 If true (the first time the user is upvoting the image)
	if (!authenticateUpvote.length) {
		//👇🏻 increases the vote count
		item[0].vote_count += 1;
		//👇🏻 adds the user ID to the list of voters
		voters.push(userID);
		//👇🏻 triggers this event to reflect the change in vote count
		socket.emit("allPhotosMessage", {
			message: "Photos retrieved successfully",
			photos: images,
		});
		//👇🏻 Returns the upvote response
		return socket.emit("upvoteSuccess", {
			message: "Upvote successful",
			item,
		});
	}
	/*
	👇🏻 nullifies duplicate votes. (if the user ID already exists in the array of voted users)
	*/
	socket.emit("upvoteError", {
		error_message: "Duplicate votes are not allowed",
	});
});
```

Listen to the likely response from the server within the `PhotoContainer.js` file.

```jsx
useEffect(() => {
	socket.on("upvoteSuccess", (data) => {
		toast.success(data.message);
		//👇🏻 logs the email of the user who owns the image.
		console.log(data.item[0]._ref);
	});
	socket.on("upvoteError", (data) => {
		toast.error(data.error_message);
	});
}, [socket]);
```

From the code snippet above, `data.item[0]._ref` is required because we want to send email notifications to the users when they upvote their images.

## How to send emails via EmailJS in React

[EmailJS](https://www.emailjs.com/) is a JavaScript library that enables us to send emails via client-side technologies only - without a server. With EmailJS, you can send texts and email templates and add attachments to the emails.

Here, I'll guide you through adding EmailJS to the React.js application and how to send emails to users whenever their images gain a vote.

Install EmailJS to the React application by running the code below:

```bash
npm install @emailjs/browser
```

Create an EmailJS account [here](https://dashboard.emailjs.com/sign-up) and add an email service provider to your account.

Create an email template as done in the image below:

![EmailJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h176coluwwzxqq26ebyh.png)

Update the `PhotoContainer.js` file to send the email template to users whenever their images gain a vote.

```jsx
import emailjs from "@emailjs/browser";

const PhotoContainer = ({ photos, socket }) => {
	const handleUpvote = (id) => {
		socket.emit("photoUpvote", {
			userID: localStorage.getItem("_id"),
			photoID: id,
		});
	};

	//👇🏻 The function sends email to the user - (to_email key)
	const sendEmail = (email) => {
		emailjs
			.send(
				"YOUR_SERVICE_ID",
				"YOUR_TEMPLATE_ID",
				{
					to_email: email,
					from_email: localStorage.getItem("_myEmail"),
				},
				"YOUR_PUBLIC_KEY"
			)
			.then(
				(result) => {
					console.log(result.text);
				},
				(error) => {
					console.log(error.text);
				}
			);
	};

	useEffect(() => {
		socket.on("upvoteSuccess", (data) => {
			toast.success(data.message);
			//👇🏻 Pass the image owner email into the function
			sendEmail(data.item[0]._ref);
		});
		socket.on("upvoteError", (data) => {
			toast.error(data.error_message);
		});
	}, [socket]);
	return <div>...</div>;
};
```

You can get your EmailJS Public key from the Account section of your EmailJS dashboard.

Congratulations! You've completed the project for this tutorial.

## Conclusion

So far, you've learnt the following:

- how to set up Socket.io in a React and Node.js application,
- create an authentication with Socket.io and React,
- communicate between a server and a client via Socket.io, and
- send emails with EmailJS.

This tutorial walks you through a project you can build using Socket.io and React. Feel free to improve the application by adding an authentication library and a real-time database.

The source code for this tutorial is available here:

[https://github.com/novuhq/blog/tree/main/upvote-app-with-react-and-nodejs](https://github.com/novuhq/blog/tree/main/upvote-app-with-react-and-nodejs)

Thank you for reading!

## Help me out!
If you feel like this article helped you understand WebSockets better! I would be super happy if you could give us a star! And let me also know in the comments ❤️
https://github.com/novuhq/novu
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5d6ugy7vbn2fl5kggbh.gif)