Member-only story

krishankant singhal
4 min readOct 1, 2024

--

Blog Post 5: Handling Asynchronous Operations in our POS System

Welcome back, developers! In our previous post, we implemented state management using TypeScript and the React Context API. Today, we’ll focus on handling asynchronous operations in our POS system, such as fetching menu items from an API and processing payments. We’ll explore how to use TypeScript with async/await and how to handle loading and error states in our application.

Let’s start by creating a service to handle our API calls:


import { MenuItem } from './types';

const API_BASE_URL = 'https://api.ourrestaurant.com'; // Replace with your actual API URL

export async function fetchMenuItems(): Promise<MenuItem[]> {
try {
const response = await fetch(`${API_BASE_URL}/menu`);
if (!response.ok) {
throw new Error('Failed to fetch menu items');
}
return await response.json();
} catch (error) {
console.error('Error fetching menu items:', error);
throw error;
}
}

export async function processPayment(orderId: number, amount: number): Promise<{ success: boolean; transactionId: string }> {
try {
const response = await fetch(`${API_BASE_URL}/process-payment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ orderId, amount }),
});
if (!response.ok) {
throw new Error('Payment processing failed');
}
return await response.json();
} catch (error) {
console.error('Error processing payment:', error);
throw error;
}
}

--

--

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