This content originally appeared on DEV Community π©βπ»π¨βπ» and was authored by Nevo David
What is this article about?
Upvotes became a great way to understand what your visitors want. You can take websites like ProductHunt, and public roadmaps like Gleap, Upvoty, Prodcamp, have the ability to let user share their thoughts (in votes).
Even Reddit, one of the most popular social media lets people upvote or downvote your posts. We are going to build something similar with images!
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.
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.
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. 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.
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.
mkdir upvote-app
cd upvote-app
mkdir client server
Navigate into the client folder via your terminal and create a new React.js project.
cd client
npx create-react-app ./
Install Socket.io client API, React Toastify, and React Router.Β React Router is a JavaScript library that enables us to navigate between pages in a React application, andΒ React Toastify is used to display colourful notifications to the users.
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.
function App() {
return (
<div>
<p>Hello World!</p>
</div>
);
}
export default App;
Add the Socket.io client API to the React app as below:
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.
cd server & npm init -y
Install Express.js, CORS, Nodemon, and Socket.io Server API.
npm install express cors nodemon socket.io react-icons
Express.jsΒ is a fast, minimalist framework that provides several features for building web applications in Node.js.Β CORSΒ is a Node.js package that allows communication between different domains.
NodemonΒ is a Node.js tool that automatically restarts the server after detecting file changes, andΒ Socket.ioΒ allows us to configure a real-time connection on the server.
Create an index.js file - the entry point to the web server.
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.
//ππ»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.
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.
//ππ» 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.
//ππ» 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.
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.
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:
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.
@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.
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;
The Register page
Copy the code below into the Register.js
file to accepts the user's email, username and password.
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;
The Photos component
This component is divided into two sub-components which are the navigation and the main container containing the available images.
Copy the code below into the Photos.js
file.
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.
touch Nav.js PhotoContainer.js
Copy the code below into the Nav.js
file.
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:
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:
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;
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 library. Within the MyPhotos
component, users can copy their profile URLs and share them with others.
React-copy-to-clipboard is a package that allows us to copy and paste contents via a button click in React.
Install theΒ React-copy-to-clipboardΒ library by running the code below.
npm install react-copy-to-clipboard
Copy the code below into the MyPhotos.js
file.
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 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.
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.
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:
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.
//ππ» 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.
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.
//ππ» 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.
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.
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:
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.
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.
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:
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.
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.
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.
useEffect(() => {
//ππ» search can be anything
socket.emit("allPhotos", "search");
}, [socket]);
Listen to the event and return all the available images on the server.
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:
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.
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.
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:
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.
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.
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:
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.
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.
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.
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Β 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:
npm install @emailjs/browser
Create an EmailJS accountΒ hereΒ and add an email service provider to your account.
Create an email template as done in the image below:
Update the PhotoContainer.js
file to send the email template to users whenever their images gain a vote.
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
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
This content originally appeared on DEV Community π©βπ»π¨βπ» and was authored by Nevo David
Nevo David | Sciencx (2022-12-05T15:24:04+00:00) Creating an upvote system with React and Socket.io π₯³ π. Retrieved from https://www.scien.cx/2022/12/05/creating-an-upvote-system-with-react-and-socket-io-%f0%9f%a5%b3-%f0%9f%94%9d/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.