October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk6 min

How to Show Errors in React and Update Card Quantities Without Mutating Other Cards

Update one React card's quantity by ID with map() and object spread, leave sibling cards untouched, and show errors through state or an Error Boundary.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To change a card’s quantity without touching the other cards, keep the cards in state, replace the array with map(), and return a new object only for the card whose ID matches. To show errors, decide first whether the failure is an expected one, such as a failed save or invalid input, or an unexpected crash during rendering. Expected failures go into component state and are rendered as messages. Rendering crashes are caught by an Error Boundary.

The question as submitted: “I am new in reactjs and capable of building a website in react. Now want to know how could I show error in react application and change quatity in all card elements without mutating other cards.”

As an Amazon Associate I earn from qualifying purchases.

Decide what “all card elements” means

The phrase can mean two different things, and the code differs for each:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • One selected card changes, the rest stay the same. This is the most common case in a shop, basket, or product list. Each button press targets one card by its ID.
  • Every card changes. For example, a “add one to every item” button. Each card is replaced by a copy, and each copy gets the new quantity.

Both approaches follow the same rule: the array and every object in state are read-only. You create replacements and pass them to the state setter.

Update quantities without mutating other cards

Why changing the object directly causes trouble

In JavaScript, card.quantity++ changes the object that already lives in state. React detects changes by comparing references, so an in-place edit can leave the screen out of date. It also changes data that other parts of the code may be reading. React’s guide to Updating Arrays in State states the rule directly: arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state.

Update one card by ID

Give every card a stable, unique id. Then use map() to build a new array. Return a new object for the matching card and the original object for everything else. The untouched cards keep their references, so they are not mutated.

import { useState } from 'react';

const initialCards = [
  { id: 'a', title: 'Starter pack', quantity: 1 },
  { id: 'b', title: 'Pro pack', quantity: 2 },
];

function Card({ card, onChange }) {
  return (
    <li>
      {card.title} - quantity {card.quantity}
      <button onClick={() => onChange(card.id, -1)}>-</button>
      <button onClick={() => onChange(card.id, 1)}>+</button>
    </li>
  );
}

export default function CardList() {
  const [cards, setCards] = useState(initialCards);

  function changeQuantity(cardId, delta) {
    setCards(previousCards =>
      previousCards.map(card =>
        card.id === cardId
          ? { ...card, quantity: Math.max(0, card.quantity + delta) }
          : card
      )
    );
  }

  return (
    <ul>
      {cards.map(card => (
        <Card key={card.id} card={card} onChange={changeQuantity} />
      ))}
    </ul>
  );
}

The Math.max(0, ...) call keeps the quantity from going below zero. Remove it if your business rules allow negative values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Update every card

If every card should change, return a copy of each one:

function addOneToEveryCard() {
  setCards(previousCards =>
    previousCards.map(card => ({ ...card, quantity: card.quantity + 1 }))
  );
}

Handle nested quantity fields

The object spread copies only the top level. If the quantity sits inside another object, such as card.product.quantity, copy each level you change:

{ ...card, product: { ...card.product, quantity: card.product.quantity + 1 } }

Use the updater form for repeated clicks

Passing a function to the setter, as in setCards(previousCards => ...), gives you the latest queued state. This matters when two updates happen before React re-renders. React’s useState reference describes this behavior. If you calculate the next array from the value captured in the current render instead, a fast double click can overwrite the first change.

Immutable replacements for common operations

Task Mutating version (avoid) Immutable version
Change one card’s quantity card.quantity += 1 { ...card, quantity: card.quantity + 1 } inside map()
Add a card cards.push(newCard) [...cards, newCard]
Remove a card cards.splice(index, 1) cards.filter(card => card.id !== cardId)
Sort cards cards.sort(...) [...cards].sort(...)

Show errors in the right place

Choose the error display based on where the failure happens:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Failure Where to handle it Typical display
Invalid input or a failed request in an event handler Component state, set in a try/catch Message next to the form, card, or button
Form action result Action state, such as useActionState Message returned by the action, shown in the form
Exception thrown while rendering a subtree An Error Boundary Fallback UI in place of the broken section

Expected failures: validation and requests

Store the error in state and clear it when the user tries again. React’s guide Reacting to Input with State models this as separate UI states, including an error state for a failed network response.

const [error, setError] = useState(null);

async function handleSave() {
  setError(null);
  try {
    await saveCards(cards);
  } catch (err) {
    setError('Could not save your changes. Please try again.');
  }
}

return (
  <>
    {error && <p role="alert">{error}</p>}
    <button onClick={handleSave}>Save</button>
  </>
);

This code is an illustration, not a tested component. Show a short user-facing message. Send the technical details to your logging or error-reporting tool, not to the screen.

Form actions with useActionState

If your form uses React’s form actions, the action can return a message and useActionState stores it for rendering inside the form. The <form> reference covers this flow and also notes that an Error Boundary can catch an error thrown by a form action. useActionState is part of React 19 and later, so check your installed version and framework before following that pattern.

Rendering errors: Error Boundaries

An Error Boundary shows fallback UI when a component below it throws during rendering. Boundaries are written as class components. The Component reference documents getDerivedStateFromError for setting the fallback state and componentDidCatch for side effects such as reporting the error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { Component } from 'react';

class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Send the error to your logging service here.
  }

  render() {
    if (this.state.hasError) {
      return <p>The cards could not be displayed.</p>;
    }
    return this.props.children;
  }
}

// Usage:
// <ErrorBoundary>
//   <CardList />
// </ErrorBoundary>

What an Error Boundary does not catch

  • Errors inside event handlers, such as a click that calls a failing function. Handle these with try/catch and state, as shown above.
  • Ordinary asynchronous callback errors, such as a rejected request that nothing catches.
  • Errors thrown by the boundary itself. The boundary must sit above the component that might fail.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decide where quantity state lives

The update pattern above assumes the parent owns the card array. That is the usual choice when cards belong to one cart or list. The alternative is to keep quantity inside each card component.

Option How updates happen Good fit Trade-off
Parent owns the array The card passes its ID to a callback. The parent maps over the array. Shared carts, totals, saving to a server The parent re-renders when any card changes
Card owns its quantity The card calls its own state setter. A quantity that only affects that card’s display The parent cannot read or save the value without extra plumbing

React’s guide to Updating Objects in State covers the same copy-then-replace approach for single objects. For a shopping cart or any list that must be saved or totalled, the parent-owned array is the safer design.

Troubleshooting checklist

  • The quantity changes in your data but the screen does not update. Look for an in-place edit such as card.quantity++ or push. Replace it with a new object or array.
  • Every card changes when you click one. The update condition is missing or wrong. Check that card.id === cardId compares the intended values.
  • The wrong card changes after you remove or reorder items. The list is keyed by array index. Use a stable id as the key.
  • Two cards share an ID. The update matches both. Make IDs unique when you create the data.
  • An error message stays on screen after a successful retry. Call setError(null) at the start of the new attempt, as in the save example.
  • An error does not reach your boundary. The failing code is in an event handler or async callback. Catch it in that code and store it in state.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.