Free tools Windows power users keep installed
One-click scans. No signup required.
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:
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →- 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.
#1 Best Overall
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.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsUpdate every card
If every card should change, return a copy of each one:
Rank #3
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.
Rank #4
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:
Recommended Free Tools
| 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.
Best Value
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.
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/catchand 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.
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.
Quick Recap
Troubleshooting checklist
- The quantity changes in your data but the screen does not update. Look for an in-place edit such as
card.quantity++orpush. 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 === cardIdcompares the intended values. - The wrong card changes after you remove or reorder items. The list is keyed by array index. Use a stable
idas thekey. - 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.




