krishankant singhal
4 min readOct 1, 2024

--

Blog Post 4: State Management with TypeScript and React Context API

Welcome back, developers! In our previous post, we built a MenuList component and explored some advanced TypeScript concepts. Today, we’ll dive into state management using TypeScript and the React Context API. We’ll create a global state for our POS system and learn how to manage it effectively.

Let’s start by defining our application state using TypeScript interfaces:


export interface MenuItem {
id: number;
name: string;
price: number;
category: string;
}
export interface OrderItem extends MenuItem {
quantity: number;
}
export interface Order {
id: number;
items: OrderItem[];
total: number;
status: 'pending' | 'completed' | 'cancelled';
}
export interface POSState {
menu: MenuItem[];
currentOrder: Order | null;
orders: Order[];
}
export interface POSContextType {
state: POSState;
addToOrder: (item: MenuItem) => void;
removeFromOrder: (itemId: number) => void;
completeOrder: () => void;
cancelOrder: () => void;
}

Now that we have our state interfaces defined, let’s create our Context and Provider:


import React, { createContext, useContext, useReducer } from ‘react’;
import { POSState, POSContextType, MenuItem, Order } from ‘./types’;
const initialState: POSState = {
menu: [], // We'll populate this later
currentOrder: null,
orders: [],
};
const POSContext = createContext<POSContextType | undefined>(undefined);
type POSAction =
| { type: 'ADD_TO_ORDER'; payload: MenuItem }
| { type: 'REMOVE_FROM_ORDER'; payload: number }
| { type…

--

--

krishankant singhal
krishankant singhal

Written by krishankant singhal

Angular,Vuejs,Android,Java,Git developer. i am nerd who want to learn new technologies, goes in depth.

No responses yet