Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Next to the address type (home, work or other) add a trash icon to delete the address...…

  1. User

    Next to the address type (home, work or other) add a trash icon to delete the address... clicking it should show confirmation message to delete the address... 'use client'; import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { useRouter } from 'next/navigation'; import Link from "next/link"; import { CircleArrowLeft, Home, Building2, PlusCircle, MapPin, Phone } from "lucide-react";

    const ChooseAddress = () => { const router = useRouter(); const [addresses, setAddresses] = useState([]); const [order, setOrder] = useState({}); const [error, setError] = useState(''); const [isSelecting, setIsSelecting] = useState(false);

    useEffect(() => {
        try {
            const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
            const storedOrder = JSON.parse(localStorage.getItem('orderData') || '{}');
            setAddresses(storedAddresses);
            setOrder(storedOrder);
            if (storedAddresses.length === 0) {
                router.push("/profile/address/add?redirect=cart/order")
            }
        } catch (err) {
            console.error('Failed to load from localStorage:', err);
            setError('Failed to load addresses. Please try again.');
        }
    }, [router]);
    
    const handleAddressSelect = useCallback((address) => {
        setIsSelecting(true);
        try {
            const updatedOrder = { ...order, shippingAddress: address };
            setOrder(updatedOrder);
            localStorage.setItem('orderData', JSON.stringify(updatedOrder));
            localStorage.setItem('lastUsedAddress', JSON.stringify(address));
            router.push('/cart/order');
        } catch (err) {
            console.error('Failed to save order data:', err);
            setError('Failed to select address. Please try again.');
        } finally {
            setIsSelecting(false);
        }
    }, [order, router]);
    
    const getAddressIcon = (type) => {
        switch (type) {
            case 'home':
                return <Home size={24} />;
            case 'work':
                return <Building2 size={24} />;
            default:
                return <PlusCircle size={24} />;
        }
    };
    
    const renderedAddresses = useMemo(() => {
        if (addresses.length === 0) {
            return;
        }
    
        return addresses.map((address, index) => (
            <div
                key={index}
                className="mb-4 p-4 bg-[#F6F3F1]/30 shadow-[0px_2px_4px_3px_rgba(0,0,0,0.1)] rounded-xl cursor-pointer hover:bg-gray-50"
                onClick={() => handleAddressSelect(address)}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        handleAddressSelect(address);
                    }
                }}
                aria-label={`Select ${address.type ? address.type.charAt(0).toUpperCase() + address.type.slice(1) : 'Other'} address`}
            >
                <div className="flex items-center mb-2">
                    {getAddressIcon(address.type)}
                    <h2 className="text-xl font-medium ml-2 capitalize">
                        {address.type
                            ? (address.type === 'home' ? 'Home' :
                                address.type === 'work' ? 'Work' : 'Other')
                            : 'Other'}
                    </h2>
                </div>
                <div className="w-full mb-4 mt-4 h-[1px] bg-[#695C5C]/30"></div>
                <div className="flex items-center text-gray-800 mb-1">
                    <MapPin size={18} className="mr-2"/>
                    <p className="capitalize">{address.governorate},&nbsp;</p>
                    <p>{`${address.city}, ${address.address}`}</p>
                </div>
                <div className="flex items-center text-gray-800">
                    <Phone size={18} className="mr-2"/>
                    <p>{address.phone_number}</p>
                </div>
            </div>
        ));
    }, [addresses, handleAddressSelect]);
    
    return (
        <div className="container mx-auto max-w-md font-sans">
            <header className="flex items-center mb-12">
                <CircleArrowLeft
                    size={52}
                    strokeWidth={0.7}
                    onClick={() => router.back()}
                    className="p-2 relative z-20 cursor-pointer"
                    aria-label="Go back"
                />
                <h1 className="text-2xl ssm:text-3xl absolute right-0 left-0 z-10 text-center font-medium">
                    Choose Address
                </h1>
            </header>
    
            {error && <p className="text-red-500 text-center mb-4">{error}</p>}
            {isSelecting && <p className="text-center text-gray-500">Selecting address...</p>}
            {!isSelecting && renderedAddresses}
    
            <Link
                className="w-full flex items-center justify-center bg-[#3B5345] text-white py-3 px-4 rounded-lg gap-1.5 font-medium text-lg mt-4 text-center"
                href={{
                    pathname: "/profile/address/add",
                    query: { redirect: "/cart/order" }
                }}
                aria-label="Add a new address"
            >
                <PlusCircle size={24} />
                Add a new address
            </Link>
        </div>
    );
    

    };

    export default React.memo(ChooseAddress);

  2. Assistant

    To implement the requested functionality, we'll make several changes to your ChooseAddress component. Here's the step-by-step guide:

    1. Import the Trash Icon: We'll use the Trash2 icon from the lucide-react library.

      import { Trash2 } from "lucide-react";
      
    2. Add the Trash Icon to Each Address Card: Modify the JSX within your renderedAddresses to include the Trash2 icon next to the address type.

      <div className="flex items-center mb-2">
          {getAddressIcon(address.type)}
          <h2 className="text-xl font-medium ml-2 capitalize">
              {address.type
                  ? (address.type === 'home' ? 'Home' :
                      address.type === 'work' ? 'Work' : 'Other')
                  : 'Other'}
          </h2>
          <Trash2
              size={24}
              className="ml-auto cursor-pointer"
              onClick={(e) => handleDeleteAddress(e, index)}
              aria-label="Delete address"
          />
      </div>
      
    3. Handle the Delete Action: Define the handleDeleteAddress function. This function will stop the event from propagating (so it doesn't trigger the handleAddressSelect), show a confirmation dialog, and update the state and local storage if the user confirms.

      const handleDeleteAddress = useCallback((e, index) => {
          e.stopPropagation();
          if (window.confirm('Are you sure you want to delete this address?')) {
              const updatedAddresses = addresses.filter((_, i) => i !== index);
              setAddresses(updatedAddresses);
              localStorage.setItem('addresses', JSON.stringify(updatedAddresses));
          }
      }, [addresses]);
      
    4. Redirect if No Addresses Remain: After deleting an address, if no addresses are left, redirect the user to the address addition page.

      useEffect(() => {
          if (addresses.length === 0) {
              router.push("/profile/address/add?redirect=cart/order");
          }
      }, [addresses, router]);
      
    5. Ensure Proper Dependency Management: Make sure all dependencies are correctly specified in your useEffect and useCallback hooks to prevent unexpected behaviors.

    Updated Component Code:

    'use client';
    import React, { useState, useEffect, useCallback, useMemo } from 'react';
    import { useRouter } from 'next/navigation';
    import Link from "next/link";
    import { CircleArrowLeft, Home, Building2, PlusCircle, MapPin, Phone, Trash2 } from "lucide-react";
    
    const ChooseAddress = () => {
        const router = useRouter();
        const [addresses, setAddresses] = useState([]);
        const [order, setOrder] = useState({});
        const [error, setError] = useState('');
        const [isSelecting, setIsSelecting] = useState(false);
    
        useEffect(() => {
            try {
                const storedAddresses = JSON.parse(localStorage.getItem('addresses') || '[]');
                const storedOrder = JSON.parse(localStorage.getItem('orderData') || '{}');
                setAddresses(storedAddresses);
                setOrder(storedOrder);
                if (storedAddresses.length === 0) {
                    router.push("/profile/address/add?redirect=cart/order")
                }
            } catch (err) {
                console.error('Failed to load from localStorage:', err);
                setError('Failed to load addresses. Please try again.');
            }
        }, [router]);
    
        useEffect(() => {
            if (addresses.length === 0) {
                router.push("/profile/address/add?redirect=cart/order");
            }
        }, [addresses, router]);
    
        const handleAddressSelect = useCallback((address) => {
            setIsSelecting(true);
            try {
                const updatedOrder = { ...order, shippingAddress: address };
                setOrder(updatedOrder);
                localStorage.setItem('orderData', JSON.stringify(updatedOrder));
                localStorage.setItem('lastUsedAddress', JSON.stringify(address));
                router.push('/cart/order');
            } catch (err) {
                console.error('Failed to save order data:', err);
                setError('Failed to select address. Please try again.');
            } finally {
                setIsSelecting(false);
            }
        }, [order, router]);
    
        const handleDeleteAddress = useCallback((e, index) => {
            e.stopPropagation();
            if (window.confirm('Are you sure you want to delete this address?')) {
                const updatedAddresses = addresses.filter((_, i) => i !== index);
                setAddresses(updatedAddresses);
                localStorage.setItem('addresses', JSON.stringify(updatedAddresses));
            }
        }, [addresses]);
    
        const getAddressIcon = (type) => {
            switch (type) {
                case 'home':
                    return <Home size={24} />;
                case 'work':
                    return <Building2 size={24} />;
                default:
                    return <PlusCircle size={24} />;
            }
        };
    
        const renderedAddresses = useMemo(() => {
            if (addresses.length === 0) {
                return;
            }
    
            return addresses.map((address, index) => (
                <div
                    key={index}
                    className="mb-4 p-4 bg-[#F6F3F1]/30 shadow-[0px_2px_4px_3px_rgba(0,0,0,0.1)] rounded-xl cursor-pointer hover:bg-gray-50"
                    onClick={() => handleAddressSelect(address)}
                    role="button"
                    tabIndex={0}
                    onKeyDown={(e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                            handleAddressSelect(address);
                        }
                    }}
                    aria-label={`Select ${address.type ? address.type.charAt(0).toUpperCase() + address.type.slice(1) : 'Other'} address`}
                >
                    <div className="flex items-center mb-2">
                        {getAddressIcon(address.type)}
                        <h2 className="text-xl font-medium ml-2 capitalize">
                            {address.type
                                ? (address.type === 'home' ? 'Home' :
                                    address.type === 'work' ? 'Work' : 'Other')
                                : 'Other'}
                        </h2>
                        <Trash2
                            size={24}
                            className="ml-auto cursor-pointer"
                            onClick={(e) => handleDeleteAddress(e, index)}
                            aria-label="Delete address"
                        />
                    </div>
                    <div className="w-full mb-4 mt-4 h-[1px] bg-[#695C5C]/30"></div>
                    <div className="flex items-center text-gray-800 mb-1">
                        <MapPin size={18} className="mr-2"/>
                        <p className="capitalize">{address.governorate},&nbsp;</p>
                        <p>{`${address.city}, ${address.address}`}</p>
                    </div>
                    <div className="flex items-center text-gray-800">
                        <Phone size={18} className="mr-2"/>
                        <p>{address.phone_number}</p>
                    </div>
                </div>
            ));
        }, [addresses, handleAddressSelect, handleDeleteAddress]);
    
        return (
            <div className="container mx-auto max-w-md font-sans">
                <header className="flex items-center mb-12">
                    <CircleArrowLeft
                        size={52}
                        strokeWidth={0.7}
                        onClick={() => router.back()}
                        className="p-2 relative z-20 cursor-pointer"
                        aria-label="Go back"
                    />
                    <h1 className="text-2xl ssm:text-3xl absolute right-0 left-0 z-10 text-center font-medium">
                        Choose Address
                    </h1>
                </header>
    
                {error && <p className="text-red-500 text-center mb-4">{error}</p>}
                {isSelecting && <p className="text-center text-gray-500">Selecting address...</p>}
                {!isSelecting && renderedAddresses}
    
                <Link
                    className="w-full flex items-center justify-center bg-[#3B5345] text-white py-3 px-4 rounded-lg gap-1.5 font-medium text-lg mt-4 text-center"
                    href={{
                        pathname: "/profile/address/add",
                        query: { redirect: "/cart/order" }
                    }}
                    aria-label="Add a new address"
                >
                    <PlusCircle size={24} />
                    Add a new address
                </Link>
            </div>
        );
    };
    
    export default React.memo(ChooseAddress);
    

    With these changes, users can now delete addresses by clicking the trash icon next to each address type. A confirmation dialog ensures that addresses aren't deleted accidentally. If all addresses are deleted, the user is redirected to add a new address, maintaining the flow of your application.