Two pages complete the social side of DevTinder: Connections (everyone you've matched with) and Requests (people who are interested in you, waiting for your answer). Both follow the pattern from Chapter S2 17: DevTinder UI - Part 3: fetch on mount, store in Redux, render a list. Requests adds actions that update the UI after the server confirms.
In this chapter you'll learn
- two more Redux slices:
connectionsandrequests - rendering lists in React with
map()and thekeyprop - a Connections page using
GET /user/connections - a Requests page using
GET /user/requests/received - accepting/rejecting with
POST /request/review/:status/:requestId, then updating Redux - why you update the UI after the API succeeds
Before you start: read Chapter S2 17: DevTinder UI - Part 3 (the feed pattern) and Chapter S2 13: ref, Populate and Thought Process of writing API's (the backend APIs used here).
The slices
// src/utils/connectionSlice.js
import { createSlice } from "@reduxjs/toolkit";
const connectionSlice = createSlice({
name: "connections",
initialState: null,
reducers: {
addConnections: (state, action) => action.payload,
removeConnections: () => null,
},
});
export const { addConnections, removeConnections } = connectionSlice.actions;
export default connectionSlice.reducer;// src/utils/connectionSlice.js
import { createSlice } from "@reduxjs/toolkit";
const connectionSlice = createSlice({
name: "connections",
initialState: null,
reducers: {
addConnections: (state, action) => action.payload,
removeConnections: () => null,
},
});
export const { addConnections, removeConnections } = connectionSlice.actions;
export default connectionSlice.reducer;// src/utils/requestSlice.js
import { createSlice } from "@reduxjs/toolkit";
const requestSlice = createSlice({
name: "requests",
initialState: null,
reducers: {
addRequests: (state, action) => action.payload,
removeRequest: (state, action) => state.filter((r) => r._id !== action.payload),
},
});
export const { addRequests, removeRequest } = requestSlice.actions;
export default requestSlice.reducer;// src/utils/requestSlice.js
import { createSlice } from "@reduxjs/toolkit";
const requestSlice = createSlice({
name: "requests",
initialState: null,
reducers: {
addRequests: (state, action) => action.payload,
removeRequest: (state, action) => state.filter((r) => r._id !== action.payload),
},
});
export const { addRequests, removeRequest } = requestSlice.actions;
export default requestSlice.reducer;Register both in the store:
reducer: {
user: userReducer,
feed: feedReducer,
connections: connectionReducer,
requests: requestReducer,
},reducer: {
user: userReducer,
feed: feedReducer,
connections: connectionReducer,
requests: requestReducer,
},removeRequest returns a new array without the reviewed request (filter never changes the original). Returning a new value from a reducer is always safe in Redux Toolkit.
Add routes for both pages inside Body (/connections and /requests) and links to them in the NavBar dropdown.
Rendering lists: map() and key
To show a list in React, turn an array of data into an array of elements with map():
{connections.map((connection) => (
<div key={connection._id}>{connection.firstName}</div>
))}{connections.map((connection) => (
<div key={connection._id}>{connection.firstName}</div>
))}Every element in a list needs a key: a value that's unique among its siblings and stable across renders. React uses keys to tell which items were added, removed or moved, so it updates only what changed. The database _id is the perfect key.
Don't use the array index as the key for lists that can change (map((item, index) => <div key={index}>). When an item is removed, every item after it gets a different index, and React may show stale content or mix up input values. It's only acceptable for static lists that never reorder.
The Connections page
// src/components/Connections.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addConnections } from "../utils/connectionSlice";
const Connections = () => {
const connections = useSelector((store) => store.connections);
const dispatch = useDispatch();
const fetchConnections = async () => {
try {
const res = await axios.get(BASE_URL + "/user/connections", { withCredentials: true });
dispatch(addConnections(res.data.data));
} catch (err) {
console.error(err);
}
};
useEffect(() => {
fetchConnections();
}, []);
if (!connections) return null;
if (connections.length === 0) {
return <h1 className="text-center my-10">No connections found</h1>;
}
return (
<div className="text-center my-10">
<h1 className="font-bold text-2xl">Connections</h1>
{connections.map((connection) => {
const { _id, firstName, lastName, photoUrl, age, gender, about } = connection;
return (
<div key={_id} className="flex items-center gap-4 m-4 p-4 rounded-lg bg-base-300 w-1/2 mx-auto">
<img alt="photo" className="w-20 h-20 rounded-full object-cover" src={photoUrl} />
<div className="text-left">
<h2 className="font-bold text-xl">{firstName + " " + (lastName || "")}</h2>
{age && gender && <p>{age + ", " + gender}</p>}
<p>{about}</p>
</div>
</div>
);
})}
</div>
);
};
export default Connections;// src/components/Connections.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addConnections } from "../utils/connectionSlice";
const Connections = () => {
const connections = useSelector((store) => store.connections);
const dispatch = useDispatch();
const fetchConnections = async () => {
try {
const res = await axios.get(BASE_URL + "/user/connections", { withCredentials: true });
dispatch(addConnections(res.data.data));
} catch (err) {
console.error(err);
}
};
useEffect(() => {
fetchConnections();
}, []);
if (!connections) return null;
if (connections.length === 0) {
return <h1 className="text-center my-10">No connections found</h1>;
}
return (
<div className="text-center my-10">
<h1 className="font-bold text-2xl">Connections</h1>
{connections.map((connection) => {
const { _id, firstName, lastName, photoUrl, age, gender, about } = connection;
return (
<div key={_id} className="flex items-center gap-4 m-4 p-4 rounded-lg bg-base-300 w-1/2 mx-auto">
<img alt="photo" className="w-20 h-20 rounded-full object-cover" src={photoUrl} />
<div className="text-left">
<h2 className="font-bold text-xl">{firstName + " " + (lastName || "")}</h2>
{age && gender && <p>{age + ", " + gender}</p>}
<p>{about}</p>
</div>
</div>
);
})}
</div>
);
};
export default Connections;Each item is already the other person, because the backend's connections API returns the user who isn't you (Chapter S2 13: ref, Populate and Thought Process of writing API's). Unlike the feed, this page fetches every time it opens (no if (connections) return), so a request you accepted a moment ago shows up immediately.
The Requests page
The received-requests API returns request documents, with the sender populated into fromUserId (Chapter S2 13: ref, Populate and Thought Process of writing API's):
{
"_id": "6705c2...", ← the REQUEST's id: needed to accept/reject
"fromUserId": { ← the SENDER (populated)
"_id": "6702a1...",
"firstName": "Aditi",
"photoUrl": "...",
"about": "..."
},
"toUserId": "6702b7...",
"status": "interested"
}{
"_id": "6705c2...", ← the REQUEST's id: needed to accept/reject
"fromUserId": { ← the SENDER (populated)
"_id": "6702a1...",
"firstName": "Aditi",
"photoUrl": "...",
"about": "..."
},
"toUserId": "6702b7...",
"status": "interested"
}So the page reads the sender's details from request.fromUserId, but uses the request's _id for the buttons:
// src/components/Requests.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addRequests, removeRequest } from "../utils/requestSlice";
const Requests = () => {
const requests = useSelector((store) => store.requests);
const dispatch = useDispatch();
const reviewRequest = async (status, requestId) => {
try {
await axios.post(
BASE_URL + "/request/review/" + status + "/" + requestId,
{},
{ withCredentials: true }
);
dispatch(removeRequest(requestId)); // only after the server confirmed
} catch (err) {
console.error(err);
}
};
const fetchRequests = async () => {
try {
const res = await axios.get(BASE_URL + "/user/requests/received", { withCredentials: true });
dispatch(addRequests(res.data.data));
} catch (err) {
console.error(err);
}
};
useEffect(() => {
fetchRequests();
}, []);
if (!requests) return null;
if (requests.length === 0) {
return <h1 className="text-center my-10">No requests found</h1>;
}
return (
<div className="text-center my-10">
<h1 className="font-bold text-2xl">Connection Requests</h1>
{requests.map((request) => {
const { firstName, lastName, photoUrl, about } = request.fromUserId;
return (
<div key={request._id} className="flex items-center justify-between m-4 p-4 rounded-lg bg-base-300 w-2/3 mx-auto">
<img alt="photo" className="w-20 h-20 rounded-full object-cover" src={photoUrl} />
<div className="text-left mx-4">
<h2 className="font-bold text-xl">{firstName + " " + (lastName || "")}</h2>
<p>{about}</p>
</div>
<div>
<button className="btn btn-primary mx-2" onClick={() => reviewRequest("rejected", request._id)}>
Reject
</button>
<button className="btn btn-secondary mx-2" onClick={() => reviewRequest("accepted", request._id)}>
Accept
</button>
</div>
</div>
);
})}
</div>
);
};
export default Requests;// src/components/Requests.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { BASE_URL } from "../utils/constants";
import { addRequests, removeRequest } from "../utils/requestSlice";
const Requests = () => {
const requests = useSelector((store) => store.requests);
const dispatch = useDispatch();
const reviewRequest = async (status, requestId) => {
try {
await axios.post(
BASE_URL + "/request/review/" + status + "/" + requestId,
{},
{ withCredentials: true }
);
dispatch(removeRequest(requestId)); // only after the server confirmed
} catch (err) {
console.error(err);
}
};
const fetchRequests = async () => {
try {
const res = await axios.get(BASE_URL + "/user/requests/received", { withCredentials: true });
dispatch(addRequests(res.data.data));
} catch (err) {
console.error(err);
}
};
useEffect(() => {
fetchRequests();
}, []);
if (!requests) return null;
if (requests.length === 0) {
return <h1 className="text-center my-10">No requests found</h1>;
}
return (
<div className="text-center my-10">
<h1 className="font-bold text-2xl">Connection Requests</h1>
{requests.map((request) => {
const { firstName, lastName, photoUrl, about } = request.fromUserId;
return (
<div key={request._id} className="flex items-center justify-between m-4 p-4 rounded-lg bg-base-300 w-2/3 mx-auto">
<img alt="photo" className="w-20 h-20 rounded-full object-cover" src={photoUrl} />
<div className="text-left mx-4">
<h2 className="font-bold text-xl">{firstName + " " + (lastName || "")}</h2>
<p>{about}</p>
</div>
<div>
<button className="btn btn-primary mx-2" onClick={() => reviewRequest("rejected", request._id)}>
Reject
</button>
<button className="btn btn-secondary mx-2" onClick={() => reviewRequest("accepted", request._id)}>
Accept
</button>
</div>
</div>
);
})}
</div>
);
};
export default Requests;Note onClick={() => reviewRequest("accepted", request._id)}: you pass a function that calls reviewRequest when clicked. Writing onClick={reviewRequest("accepted", request._id)} would call it immediately during render, for every request.
We built both pages and slices in a test project to check that they compile.
Pessimistic vs optimistic updates
This page updates Redux after the API call succeeds. That's a pessimistic update: the UI waits for the server's confirmation. If the request fails (network error, already reviewed), the card stays, which is correct.
The alternative is an optimistic update: remove the card immediately, then call the API, and put it back if the call fails. It feels faster, but needs rollback code. Apps like chat and likes often use optimistic updates; for actions that matter (payments, accepting connections), pessimistic is the safer default.
Common mistakes
- Using
fromUserId._id(the sender) instead ofrequest._idfor review calls: the backend looks up a request ID, so it returns 404. - Missing or index-based
keys in lists. onClick={fn(args)}instead ofonClick={() => fn(args)}: runs on render.- Updating Redux before the API confirms, without rollback.
- Mixing up response shapes: these APIs return
{ data: [...] }, so the list isres.data.data.
Key takeaways
- One slice per kind of data:
connectionsandrequests, with reducers to add and remove. - Render lists with
map()and a unique, stablekey(the_id), never the index for changing lists. - Connections:
GET /user/connectionsreturns the other users directly. - Requests:
GET /user/requests/receivedreturns requests with the sender infromUserId; review with the request's_id. - After
POST /request/review/...succeeds,dispatch(removeRequest(id))updates the list without a refresh: a pessimistic update.
Interview questions
Q1. Why does React need a key when rendering lists?
Keys let React's reconciliation identify which list items changed, were added or were removed between renders, so it can update the DOM efficiently and keep each item's state attached to the right element. Keys must be unique among siblings and stable; database IDs are ideal.
Q2. Why is using the array index as a key a problem?
When items are inserted, removed or reordered, indexes shift, so React associates the wrong state or DOM node with the wrong item: stale inputs, wrong animations, unnecessary re-renders. Index keys are only safe for static lists that never change order.
Q3. What's the difference between optimistic and pessimistic UI updates?
A pessimistic update changes the UI only after the server confirms success: simple and always consistent, but slower to feel. An optimistic update changes the UI immediately, assuming success, and rolls back if the request fails: snappier, but it requires rollback and error handling.
Q4. Why must a Redux reducer not mutate state directly (and why does createSlice seem to allow it)?
Redux detects changes by comparing references, so reducers must produce new state objects instead of mutating existing ones; otherwise components may not re-render, and time-travel debugging breaks. Redux Toolkit's createSlice uses Immer, which lets you write mutating-looking code (state.items.push(x)) and turns it into an immutable update behind the scenes. Returning a new value (like filter) works too.
Q5. What's the difference between onClick={handle} and onClick={() => handle(id)}?
onClick={handle} passes the function itself; React calls it with the event on click. onClick={() => handle(id)} passes a new function that calls handle with an argument on click. Writing onClick={handle(id)} calls handle during render and passes its return value, which is a common bug.
What's next
One feature is left: the Interested / Ignore buttons on the feed, plus a signup form. Chapter S2 19: DevTinder UI - Part 5 finishes the DevTinder UI.