1.10.12.3. fejezet, programozáskor elkövetett gyakori hibák

Kapcsolódó hivatkozások

  • Common beginner mistakes
  • UseState

    / ❌ Mutates an existing object
    function handleAddItem(value) {
      items.push(value);
      setItems(items);
    }
    // ✅ Creates a new object
    function handleAddItem(value) {
      const nextItems = [...items, value];
      setItems(nextItems);
    }
    // ❌ Mutates an existing object
    function handleChangeEmail(nextEmail) {
      user.email = nextEmail;
      setUser(user);
    }
    // ✅ Creates a new object
    function handleChangeEmail(email) {
      const nextUser = { ...user, email: nextEmail };
      setUser(nextUser);
    }

    Lista kulcsok használata

    // ❌ using index as key
    function ShoppingList({ items }) {
      return (
        <ul>
          {items.map((item, index) => {
            return (
              <li key={index}>{item}</li>
            );
          })}
        </ul>
      );
    }
    // ✅ generate an unique uuid
    function handleAddItem(value) {
      const nextItem = {
        id: crypto.randomUUID(),
        label: value,
      };
      const nextItems = [...items, nextItem];
      setItems(nextItems);
    }
     
    function ShoppingList({ items }) {
      return (
        <ul>
          {items.map((item, index) => {
            return (
              <li key={item.id}>
                {item.label}
              </li>
            );
          })}
        </ul>
      );
    }
     
    // ❌ This is a bad idea (every refresh time updated)
    <li key={crypto.randomUUID()}>
      {item.label}
    </li>
     
    // ✅ Set uuid after fetch
    const [data, setData] = React.useState(null);
    async function retrieveData() {
      const res = await fetch('/api/data');
      const json = await res.json();
      // The moment we have the data, we generate
      // an ID for each item:
      const dataWithId = json.data.map(item => {
        return {
          ...item,
          id: crypto.randomUUID(),
        };
      });
      // Then we update the state with
      // this augmented data:
      setData(dataWithId);
    }

    State értékének olvasása módosítás után

    // Uses `const`, not `let`, and so it can't be reassigned
    const [count, setCount] = React.useState(0);
    count = count + 1; // Uncaught TypeError:
                       // Assignment to constant variable
     
    //❌ This is the problematic code:
    function handleClick() {
      setCount(count + 1);
      console.log({ count }); // return count-1
    }
     
    // ✅ use value as new count
    function handleClick() {
      const nextCount = count + 1;
      setCount(nextCount);
      // Use `nextCount` whenever we want
      // to reference the new value:
      console.log({ nextCount });
    }

    Async useEffect

    //❌ This is the problematic code:
    React.useEffect(async () => {
      const url = `${API}/get-profile?id=${userId}`;
      const res = await fetch(url);
      const json = await res.json();
      setUser(json);
    }, [userId]);
     
    // ✅ use an internal function
    React.useEffect(() => {
      // Create an async function...
      async function runEffect() {
        const url = `${API}/get-profile?id=${userId}`;
        const res = await fetch(url);
        const json = await res.json();
        setUser(json);
      }
      // ...and then invoke it:
      runEffect();
    }, [userId]);