Context Reducer
Learn how to use the venueReducer method and its five actions along with its types.
We'll cover the following...
The context reducer looks like this:
Press + to interact
import { AppProps } from "components/app"import { VenueState, VenueAction } from "contexts/venue_types"export const initialState = (props: AppProps): VenueState => {return {rowCount: props.rowCount,seatsPerRow: props.seatsPerRow,concertId: props.concertId,otherTickets: [],ticketsToBuyCount: 1,myTickets: [],}}export const venueReducer = (state: VenueState,action: VenueAction): VenueState => {switch (action.type) {case "setTickets":return {...state,otherTickets: action.tickets.filter((ticket) => ticket.status === "purchased"),myTickets: action.tickets.filter((ticket) => ticket.status === "held"),}case "setTicketsToBuy":return { ...state, ticketsToBuyCount: action.amount }case "holdTicket": {const newTickets = Array.from(Array(state.ticketsToBuyCount).keys()).map((index) => {return {id: 0,row: action.rowNumber,number: action.seatNumber + index,status: "held",}})return {...state,myTickets: [...state.myTickets, ...newTickets],}}case "unholdTicket": {const newTickets = state.myTickets.filter((ticket) => {const rowMatch = ticket.row == action.rowNumberconst seatDiff = ticket.number - action.seatNumberconst seatMatch =seatDiff >= 0 && seatDiff < state.ticketsToBuyCountreturn !(rowMatch && seatMatch)})return { ...state, myTickets: newTickets }}case "clearHolds": {return { ...state, myTickets: [] }}default:return state}}
What’s interesting is that almost none of this is React-specific.
We define two methods
- The first,
initialState
, creates an initial state from the incoming props passed to the app. The return type of the state is calledVenueState
and is defined in thevenue_types
file. - The second method is
venueReducer
, the reducer function itself. All our business logic has been reworked to match the reducer pattern. The logic has been reworked to use the state coming into the reducer function and return a new state object with the changes.
The venueReducer
method
There are five actions in the venueReducer
, all of which return a new state object. They all use the JavaScript spread operator heavily, which makes it clear that an object should be copied but specific fields should be overridden. The JS { ...state, ticketsToBuyCount: action.amount }
creates a new object ...