Objects in State
Values that belong together can share one state, as an object. A ticket order has a type and a count:
const [ticket, setTicket] = useState({ type: "Weekend", count: 1 });The page reads it as any object: {ticket.count} × {ticket.type} shows 1 × Weekend. Changing it follows the same rule as arrays: don't change the object in state (ticket.count = 2 shows nothing new), make a new one. Spread copies the object, and a property written after it replaces the copy's:
const newTicket = { ...ticket, count: 2 };newTicket has everything ticket had, type too, and count 2. Without the spread, setTicket({ count: 2 }) would lose type: a setter replaces the whole state, it doesn't merge the new object into the old one.
Like the new arrays, a new object made from the old one goes into an updater function. Here it adds 1 to the count. One detail: when an arrow function returns an object, the object needs parentheses around it:
function handleMore() {
setTicket((ticket) => ({ ...ticket, count: ticket.count + 1 }));
}Without them, the curly braces would be the body of the function, as in (ticket) => { return …; }, and ...ticket in a body is a mistake: the red message under the preview says Unexpected token, expected ",", and the app doesn't run. The parentheses make the curly braces an object, which the arrow function returns.
Two state variables, type and count, would work too. An object is handy when the values describe one thing and change together, like a ticket order.
Instructions
Make ticket a state with the same starting object. One more adds 1 to its count, with a new object made with spread.
Make the buttons Friday, Saturday and Weekend change the ticket's type, and keep its count.