You uncheck “Email me a weekly digest,” hit Save, and refresh the page. The box is checked again.
You open the Network tab and try one more time. The browser sends {"weeklyDigest": false}. The server responds with {"weeklyDigest": true}. Where did your “no” turn into a “yes”?
Here’s the line that did it:
const weeklyDigest = update.weeklyDigest || saved.weeklyDigest;
It’s easy to read that as “use the new setting if the user sent one.” But when someone unsubscribes, the expression becomes false || true. The result is true, so the old preference wins.
The sneaky part? Turning the digest on works. If that’s the only direction you test, you’ll ship it.
What should an empty update mean?
Say someone changes their display name. The browser sends {"displayName": "Sam"} and leaves out weeklyDigest. Keeping the saved preference makes sense. When the browser sends {"weeklyDigest": false}, though, the user has explicitly asked to unsubscribe.
For an optional boolean setting, the ?? operator handles both cases. It falls back to the saved value when the incoming value is null or undefined. An explicit false goes through.
function nextWeeklyDigest(saved, update) {
return update.weeklyDigest ?? saved.weeklyDigest;
}
The test I’d keep
Start with someone who’s already subscribed. Then try the two updates the old code treated the same way:
const subscriber = { weeklyDigest: true };
// Editing a name should preserve the subscription.
console.assert(
nextWeeklyDigest(subscriber, { displayName: "Sam" }) === true
);
// Unchecking the box should cancel it.
console.assert(
nextWeeklyDigest(subscriber, { weeklyDigest: false }) === false
);
Swap ?? back to ||. The first check still passes. The second one catches the bug.
That’s the test I’d want in a pull request for an unsubscribe feature. Start with the emails turned on, turn them off, and check what actually got saved.
Top comments (0)