Validate the phone number to be iraqi number (it can either starts with 0 or no) 11 digits...
Also choose address should automatically saves the address and then redirects to orders/page
'use client'
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from "next/link";
import { CircleArrowLeft } from "lucide-react";
}
Also improve stability especially for safari users... and improve performance...
To address your requirements, we'll implement the following enhancements:
Phone Number Validation: Ensure that the phone number entered is a valid Iraqi number, adhering to the following rules:
Length: Exactly 11 digits.
Prefix: Can start with 0 or not.
Automatic Address Saving and Redirection: When a user selects an address, it should be automatically saved, and the user should be redirected seamlessly to the orders page.
Stability and Performance Improvements:
Local Storage Handling: Add error handling for localStorage operations to ensure compatibility across all browsers, including Safari.
Performance Optimizations: Utilize React best practices such as useCallback, useMemo, and React.memo to prevent unnecessary re-renders.
Safari Compatibility: Address any known issues with Safari, particularly around localStorage and event handling.
Below are the updated components with the necessary modifications and improvements:
1. AddAddress.jsx
Changes Made:
Phone Number Validation: Implemented regex to validate Iraqi phone numbers.
Enhanced Error Handling: Added error messages for invalid phone numbers.
Performance Optimizations: Utilized useCallback for the handleInputChange and handleSubmit functions.
Regex Pattern: The regex ^0?\d{10}$ ensures that the phone number:
Optionally starts with a 0.
Followed by exactly 10 digits, making the total length 11 digits if it starts with 0, or 10 digits otherwise. However, to strictly enforce 11 digits regardless of the prefix, you might need to adjust the regex. If you always require 11 digits regardless of the 0 prefix, use ^(0)?\d{10}$.
Error Handling: If the phone number does not match the pattern, an error message is displayed, and the form submission is halted.
Address Type Validation:
Ensures that the user selects an address type (home, work, or other). If not, an error message is displayed.
Error Handling:
Implemented error messages for both phone number validation and a general error in case localStorage operations fail.
Performance Optimizations:
useCallback is used for handleInputChange and handleSubmit to prevent unnecessary re-creations of these functions on each render.
Accessibility:
Added aria-label to interactive elements for better accessibility.
2. ChooseAddress.jsx
Changes Made:
Local Storage Error Handling: Added try-catch blocks to handle any potential errors with localStorage, improving compatibility with browsers like Safari.
Performance Optimizations: Utilized useCallback for handleAddressSelect to prevent unnecessary re-renders.
Memoization: Wrapped the addresses rendering in useMemo for better performance.
Accessibility Enhancements: Added aria-label and other accessibility attributes.
Updated Code:
jsx
Explanation:
Local Storage Error Handling:
Wrapped localStorage operations inside try-catch blocks to catch and handle any errors, which is crucial for browsers like Safari where localStorage can fail in certain scenarios (e.g., private mode).
Performance Optimizations:
useCallback: Used for handleAddressSelect to memoize the function and prevent unnecessary re-creations.
useMemo: Used for rendering the list of addresses to prevent re-rendering the list unless addresses or handleAddressSelect changes.
React.memo: Wrapped the component export with React.memo to prevent unnecessary re-renders when props haven't changed.
Accessibility Enhancements:
Added role="button" and tabIndex={0} to address containers to make them keyboard accessible.
Implemented onKeyPress to allow selection via keyboard (Enter or Space keys).
Added aria-label for better screen reader support.
User Feedback:
Displayed a user-friendly message when no addresses are found.
Displayed error messages when localStorage operations fail.
3. CartCheckout.jsx
Changes Made:
Improved Local Storage Handling: Added error handling around localStorage operations.
Performance Optimizations: Used useCallback and useMemo effectively.
Stability Enhancements: Ensured that router.prefetch is only called when necessary and handled possible undefined values gracefully.
Updated Code:
jsx
Explanation:
Local Storage Error Handling:
Wrapped localStorage access in try-catch blocks to handle cases where localStorage might be unavailable or fail, especially in browsers like Safari in private mode.
Performance Optimizations:
useCallback and useMemo: Used effectively for functions and computations that depend on certain dependencies to prevent unnecessary re-renders.
React.memo: Wrapped the component export with React.memo to prevent unnecessary re-renders when props haven’t changed.
User Feedback:
Added a generic error state to display any unexpected errors during the checkout process.
Prefetch Error Handling:
Added a .catch to the router.prefetch to handle any prefetching errors gracefully.
Accessibility Enhancements:
Ensured that all interactive elements have appropriate aria-labels for better accessibility.
Code Cleanliness:
Removed unnecessary return statements and added meaningful console error logs for easier debugging.
4. General Stability and Performance Enhancements
Handling localStorage Safely:
To ensure that localStorage operations are safe across all browsers, especially Safari, you can create utility functions that handle these operations gracefully.
import { safeLocalStorage } from '@/utils/localStorage';
// To get an item
const storedAddresses = JSON.parse(safeLocalStorage.getItem('addresses') || '[]');
// To set an item
safeLocalStorage.setItem('addresses', JSON.stringify(updatedAddresses));
Lazy Loading and Code Splitting:
Ensure that components are loaded only when needed to improve initial load performance.
jsx
// Example of dynamic import with Next.js
import dynamic from 'next/dynamic';
const CartCheckout = dynamic(() => import('@/components/CartCheckout'), {
loading: () => <p>Loading...</p>,
});
Avoid Unnecessary Re-renders:
Ensure that components only re-render when necessary by correctly setting dependencies in hooks and memoizing components/functions that don’t change frequently.
Summary
By implementing the above changes:
Validation: The phone number validation ensures data integrity for Iraqi phone numbers.
Error Handling: Enhanced error handling around localStorage operations and network requests improves stability across all browsers, including Safari.
Performance: Utilizing React's memoization techniques and optimizing component structures ensures better performance and responsiveness.
Accessibility: Improved accessibility features make the application more user-friendly for all users.
These enhancements collectively improve the robustness, user experience, and maintainability of your application.