This chapter finishes the DevTinder UI. You'll wire up the feed's Ignore and Interested buttons, add a signup form that shares code with login, send new users straight to their profile, and let users edit their skills. Then you'll look at what "real-time" means and what's still missing before launch.
In this chapter you'll learn
- sending connection requests from the feed, and removing the card afterwards
- one reusable form for both login and signup
- logging new users in automatically after signup, and redirecting them to their profile
- turning a comma-separated input into a skills array
- what "real-time" really means here, and where WebSockets would come in
Before you start: read Chapter S2 17: DevTinder UI - Part 3 (feed, UserCard) and Chapter S2 12: Logical DB Query and Compound Indexes (the send-request API).
Swiping: Ignore and Interested
Each button calls the send-request API from Chapter S2 12: Logical DB Query and Compound Indexes, POST /request/send/:status/:toUserId, with status ignored or interested. After the server confirms, the card is removed from the feed in Redux, so the next profile appears.
// src/components/UserCard.jsx
import axios from "axios";
import { useDispatch } from "react-redux";
import { BASE_URL } from "../utils/constants";
import { removeUserFromFeed } from "../utils/feedSlice";
const UserCard = ({ user, showActions = true }) => {
const { _id, firstName, lastName, photoUrl, age, gender, about, skills } = user;
const dispatch = useDispatch();
const handleSendRequest = async (status, userId) => {
try {
await axios.post(
BASE_URL + "/request/send/" + status + "/" + userId,
{},
{ withCredentials: true }
);
dispatch(removeUserFromFeed(userId)); // next card appears automatically
} catch (err) {
console.error(err);
}
};
return (
<div className="card bg-base-300 w-96 shadow-sm">
<figure>
<img src={photoUrl} alt="photo" />
</figure>
<div className="card-body">
<h2 className="card-title">{firstName + " " + (lastName || "")}</h2>
{age && gender && <p>{age + ", " + gender}</p>}
<p>{about}</p>
{skills?.length > 0 && (
<div className="flex flex-wrap gap-2">
{skills.map((skill) => (
<span key={skill} className="badge badge-outline">{skill}</span>
))}
</div>
)}
{showActions && (
<div className="card-actions justify-center my-4">
<button className="btn btn-primary" onClick={() => handleSendRequest("ignored", _id)}>
Ignore
</button>
<button className="btn btn-secondary" onClick={() => handleSendRequest("interested", _id)}>
Interested
</button>
</div>
)}
</div>
</div>
);
};
export default UserCard;// src/components/UserCard.jsx
import axios from "axios";
import { useDispatch } from "react-redux";
import { BASE_URL } from "../utils/constants";
import { removeUserFromFeed } from "../utils/feedSlice";
const UserCard = ({ user, showActions = true }) => {
const { _id, firstName, lastName, photoUrl, age, gender, about, skills } = user;
const dispatch = useDispatch();
const handleSendRequest = async (status, userId) => {
try {
await axios.post(
BASE_URL + "/request/send/" + status + "/" + userId,
{},
{ withCredentials: true }
);
dispatch(removeUserFromFeed(userId)); // next card appears automatically
} catch (err) {
console.error(err);
}
};
return (
<div className="card bg-base-300 w-96 shadow-sm">
<figure>
<img src={photoUrl} alt="photo" />
</figure>
<div className="card-body">
<h2 className="card-title">{firstName + " " + (lastName || "")}</h2>
{age && gender && <p>{age + ", " + gender}</p>}
<p>{about}</p>
{skills?.length > 0 && (
<div className="flex flex-wrap gap-2">
{skills.map((skill) => (
<span key={skill} className="badge badge-outline">{skill}</span>
))}
</div>
)}
{showActions && (
<div className="card-actions justify-center my-4">
<button className="btn btn-primary" onClick={() => handleSendRequest("ignored", _id)}>
Ignore
</button>
<button className="btn btn-secondary" onClick={() => handleSendRequest("interested", _id)}>
Interested
</button>
</div>
)}
</div>
</div>
);
};
export default UserCard;removeUserFromFeedwas added to the feed slice in Chapter S2 17: DevTinder UI - Part 3: it filters that user out. TheFeedcomponent showsfeed[0], so the next user moves into view.- The status strings must match the backend exactly:
ignoredandinterested(Chapter S2 11: Diving into the APIs and Express router). showActionsis a prop with a default value. The edit-profile preview reusesUserCard, but swiping on your own profile makes no sense, so it renders<UserCard user={...} showActions={false} />.
One form for login and signup
Login and signup forms are almost identical: signup just adds first and last name. Instead of two components, use one with a toggle:
// src/components/Login.jsx
const [isLoginForm, setIsLoginForm] = useState(true);
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
// ...emailId, password, error, dispatch, navigate as in S2 16
const handleSignUp = async () => {
try {
const res = await axios.post(
BASE_URL + "/signup",
{ firstName, lastName, emailId, password },
{ withCredentials: true }
);
dispatch(addUser(res.data.data));
navigate("/profile"); // new users go straight to completing their profile
} catch (err) {
setError(err?.response?.data || "Something went wrong");
}
};
return (
<div className="card bg-base-300 w-96 mx-auto my-10">
<div className="card-body">
<h2 className="card-title justify-center">{isLoginForm ? "Login" : "Sign Up"}</h2>
{!isLoginForm && (
<>
<input className="input input-bordered" placeholder="First name"
value={firstName} onChange={(e) => setFirstName(e.target.value)} />
<input className="input input-bordered" placeholder="Last name"
value={lastName} onChange={(e) => setLastName(e.target.value)} />
</>
)}
{/* email and password inputs, as before */}
<p className="text-red-500">{error}</p>
<button className="btn btn-primary" onClick={isLoginForm ? handleLogin : handleSignUp}>
{isLoginForm ? "Login" : "Sign Up"}
</button>
<p className="cursor-pointer text-center" onClick={() => setIsLoginForm((value) => !value)}>
{isLoginForm ? "New user? Sign up here" : "Existing user? Login here"}
</p>
</div>
</div>
);// src/components/Login.jsx
const [isLoginForm, setIsLoginForm] = useState(true);
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
// ...emailId, password, error, dispatch, navigate as in S2 16
const handleSignUp = async () => {
try {
const res = await axios.post(
BASE_URL + "/signup",
{ firstName, lastName, emailId, password },
{ withCredentials: true }
);
dispatch(addUser(res.data.data));
navigate("/profile"); // new users go straight to completing their profile
} catch (err) {
setError(err?.response?.data || "Something went wrong");
}
};
return (
<div className="card bg-base-300 w-96 mx-auto my-10">
<div className="card-body">
<h2 className="card-title justify-center">{isLoginForm ? "Login" : "Sign Up"}</h2>
{!isLoginForm && (
<>
<input className="input input-bordered" placeholder="First name"
value={firstName} onChange={(e) => setFirstName(e.target.value)} />
<input className="input input-bordered" placeholder="Last name"
value={lastName} onChange={(e) => setLastName(e.target.value)} />
</>
)}
{/* email and password inputs, as before */}
<p className="text-red-500">{error}</p>
<button className="btn btn-primary" onClick={isLoginForm ? handleLogin : handleSignUp}>
{isLoginForm ? "Login" : "Sign Up"}
</button>
<p className="cursor-pointer text-center" onClick={() => setIsLoginForm((value) => !value)}>
{isLoginForm ? "New user? Sign up here" : "Existing user? Login here"}
</p>
</div>
</div>
);<>...</>is a Fragment: it groups elements without adding an extra<div>to the page.setIsLoginForm((value) => !value)uses the updater form ofsetState: it receives the current value, which is the safe way to flip a boolean.
Log the user in right after signup
For navigate("/profile") to work, the new user must already be logged in. Otherwise Body's session check gets a 401 and sends them back to /login (Chapter S2 17: DevTinder UI - Part 3). So the backend's signup route should do what login does: create the JWT cookie and return the user (without the password hash):
// backend: src/routes/auth.js
authRouter.post("/signup", async (req, res) => {
try {
validateSignupData(req);
const { firstName, lastName, emailId, password } = req.body;
const passwordHash = await bcrypt.hash(password, 10);
const user = new User({ firstName, lastName, emailId, password: passwordHash });
const savedUser = await user.save();
const token = savedUser.getJWT(); // schema method from S2 10
res.cookie("token", token, { httpOnly: true, sameSite: "lax", maxAge: 24 * 60 * 60 * 1000 });
const { password: _, ...safeUser } = savedUser.toObject();
res.status(201).json({ message: "User added successfully", data: safeUser });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});// backend: src/routes/auth.js
authRouter.post("/signup", async (req, res) => {
try {
validateSignupData(req);
const { firstName, lastName, emailId, password } = req.body;
const passwordHash = await bcrypt.hash(password, 10);
const user = new User({ firstName, lastName, emailId, password: passwordHash });
const savedUser = await user.save();
const token = savedUser.getJWT(); // schema method from S2 10
res.cookie("token", token, { httpOnly: true, sameSite: "lax", maxAge: 24 * 60 * 60 * 1000 });
const { password: _, ...safeUser } = savedUser.toObject();
res.status(201).json({ message: "User added successfully", data: safeUser });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});Sending new users to /profile first is a small onboarding step: they add a photo, age and skills before appearing in other people's feeds.
Editing skills
skills is an array in the database (Chapter S2 08: Data Sanitization & Schema Validations), but a text input holds a string. Convert between them: show the array joined with commas, and split the text back into an array as the user types:
// in EditProfile
const [skillsText, setSkillsText] = useState((user.skills || []).join(", "));
const parseSkills = (text) => {
const list = text
.split(",") // "Node.js, React,, " → ["Node.js", " React", "", " "]
.map((s) => s.trim()) // remove spaces around each item
.filter(Boolean); // drop empty strings
return [...new Set(list)]; // remove duplicates (the Set trick from S2 14)
};
// send it with the other fields:
// { firstName, ..., skills: parseSkills(skillsText) }// in EditProfile
const [skillsText, setSkillsText] = useState((user.skills || []).join(", "));
const parseSkills = (text) => {
const list = text
.split(",") // "Node.js, React,, " → ["Node.js", " React", "", " "]
.map((s) => s.trim()) // remove spaces around each item
.filter(Boolean); // drop empty strings
return [...new Set(list)]; // remove duplicates (the Set trick from S2 14)
};
// send it with the other fields:
// { firstName, ..., skills: parseSkills(skillsText) }We checked it: "Node.js, React,, node.js ,React " becomes ["Node.js", "React", "node.js"]. Note that Set is case-sensitive, so Node.js and node.js both stay. Lowercase the values first if you want to treat them as the same.
Show skills as badges in UserCard (as in the code above), and pass skills to the live preview so it updates while typing. The backend still enforces its own limits (like at most 10 skills), so show its error message if the save fails.
What "real-time" means here
When you click Interested, the card disappears instantly. That's an instant UI update: your own action updated your own screen. It's not real-time in the networking sense: if someone else sends you a request right now, your Requests page won't show it until you reload or open the page again.
True real-time features (live notifications, chat) need the server to push data to the browser. HTTP can't do that, because it only answers requests (Chapter 11: Creating the Server). The usual tools:
- WebSockets (often with Socket.IO): a persistent two-way connection; either side can send at any time
- Server-Sent Events (SSE): a one-way stream from server to browser
- Polling: asking the server every few seconds (simple, but wasteful)
A DevTinder chat feature would be the natural next step to practise WebSockets.
Before launch: a checklist
- Every API call uses
withCredentials: true - Logout clears all user-specific slices
- Error messages from the API are shown to the user
- The feed loads more users (page 2) when it runs out
- Images have fallbacks; the layout works on mobile
-
BASE_URLwill point to the production API (Chapter S3 02: Nginx and Backend Node App Development)
Key takeaways
- Ignore/Interested call
POST /request/send/:status/:userId, thenremoveUserFromFeedshows the next card. - Reuse components with props (
showActions) and a toggle (isLoginForm) instead of duplicating them. - After signup, the backend should set the JWT cookie and return the user, so the app can go straight to
/profile. - Convert skills between a comma-separated string (input) and an array (database) with
split,trim,filter(Boolean)andSet. - Instant UI updates are not real-time: server push needs WebSockets, SSE or polling.
Interview questions
Q1. What is a React Fragment?
<>...</> (or <React.Fragment>) groups multiple elements without adding an extra DOM node. Components must return a single root, and a Fragment satisfies that without an unnecessary wrapper <div>, which can break layouts like flex, grid or tables. Use <React.Fragment key={...}> when you need a key in a list.
Q2. Why use the updater form of setState, e.g. setCount(c => c + 1)?
State updates are batched and applied asynchronously, so reading the current variable inside a handler can give a stale value, especially with several updates in a row. The updater form receives the latest state, so setCount(c => c + 1) called twice correctly adds 2.
Q3. What are WebSockets, and when would you use them over HTTP?
WebSockets are a protocol for a persistent, full-duplex connection between client and server, started by an HTTP "upgrade" request. Either side can send messages at any time with low overhead. Use them when the server must push updates instantly (chat, live notifications, multiplayer games, collaborative editing); use plain HTTP for request/response operations.
Q4. What's the difference between WebSockets, Server-Sent Events and polling?
Polling repeatedly sends normal HTTP requests to check for updates: simple, but wasteful and delayed. Server-Sent Events keep one HTTP connection open for a one-way stream from server to client, with automatic reconnection. WebSockets provide two-way messaging over one persistent connection. Pick the simplest one that fits the need.
Q5. How do you make a component reusable in React?
Make it depend on props instead of hardcoded data or global state, give optional behaviour props with sensible defaults (like showActions = true), keep side effects out of purely visual components where possible, and let parents decide layout. The same UserCard can then serve the feed and the profile preview.
What's next
DevTinder works on your machine. Season 3 puts it on the internet: in Chapter S3 01: Lanching an AWS Instance and Deploying frontend you'll launch a server on AWS EC2 and deploy the frontend with Nginx.