Skip to content

[Suggestion]: Fix the data.js file part of the solution for Challenge 4 in "Choosing the State Structure" chapter #7394

Open
@yedhink

Description

Summary

The data.js provided in the solution for "Challenge 4" has a property called isStarred which is unused in the provided solution for the challenge:

export const letters = [{
  id: 0,
  subject: 'Ready for adventure?',
-  isStarred: true,
}, {

Thus my suggestion is to remove the isStarred property from data.js file in challenge 4

Page

https://react.dev/learn/choosing-the-state-structure#recap

Details

The presence of the unused isStarred property can potentially confuse a beginner following the documentation, because they might have gone through the section on Avoiding Redundant States. I mean to say that they might end up writing a solution which utilises the isStarred property like shown below, which also solves the challenge:

import { useState } from 'react';
+import { letters as initialLetters } from './data.js';
import Letter from './Letter.js';

export default function MailClient() {
+  const [letters, setLetters] = useState(initialLetters);

+  const selectedCount = letters.filter(({isStarred}) => isStarred).length;

  function handleToggle(toggledId) {
+    setLetters(letters => letters.map(letter => {
+     if (letter.id === toggledId) {
+        return { 
+         ...letter,
+          isStarred: !letter.isStarred
+       }
+      } else return letter;
+   }))
  }

  return (
    <>
      <h2>Inbox</h2>
      <ul>
        {letters.map(letter => (
          <Letter
            key={letter.id}
            letter={letter}
+           isSelected={letter.isStarred}
            onToggle={handleToggle}
          />
        ))}
        <hr />
        <p>
          <b>
            You selected {selectedCount} letters
          </b>
        </p>
      </ul>
    </>
  );
}

Although the above solution works, it has the following cons:

  • Tight Coupling: Overloading isStarred for both "selected" and "starred" behaviours creates coupling between two potentially distinct concepts. If the app later needs to treat "starred" and "selected" as separate attributes, refactoring will be necessary.
  • Side Effects: Modifying isStarred might have unintended consequences elsewhere in the app if other features or components depend on it strictly representing "starred" status.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions