Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

update it to fetch from the following api: "https://api.naayiq.com/coupons" instead of…

  1. User

    update it to fetch from the following api: "https://api.naayiq.com/coupons" instead of existing dummy data...

    it will return a json like this:

    0id4code"a"name"a"description"Test"discount_amount"3000.00"discount_percentagenullstart_date"2024-07-16T00:00:00.000Z"end_date"2024-10-16T00:00:00.000Z"usage_limit100min_purchase_amount"1000.00"max_discount_amount"2500.00"is_activetruecoupon_image"2079.webp"created_at"2024-09-17T14:39:02.997Z"updated_at"2024-09-17T14:39:02.997Z"1id5code"naayiraq"name"naayiraq"description"Thanks for using our platform, enjoy your 10% discount!"discount_amountnulldiscount_percentage"10.00"start_date"2024-09-17T00:00:00.000Z"end_date"2024-09-25T00:00:00.000Z"usage_limit0min_purchase_amount"50000.00"max_discount_amount"10000.00"is_activetruecoupon_image"2119.jpeg"created_at"2024-09-17T21:33:42.024Z"updated_at"2024-09-17T21:34:59.525Z"

    Fetch this api in the server side and then pass the required data to the coupon

    import MyCoupons from "@/components/Coupon"; import Footer from "@/components/Footer";

    export default function CouponPage() { return ( ) }

    'use client' import React, { useState } from 'react'; import Image from "next/image"; import {useRouter} from "next/navigation"; import {CircleArrowLeft} from "lucide-react";

    const coupons = [ { type: 'Mother Day Coupons', code: 'M-Day25', validTill: 'Valid Till-22 Mar 2025', image: '/mom.png', bgColor: 'bg-pink-50', buttonColor: 'bg-[#FF81AE]/5 border-[#FF81AE]' }, { type: 'Free Delivery Coupons', code: 'Free40', validTill: 'Valid Till-Today 12 am', image: '/car.png', bgColor: 'bg-blue-50', buttonColor: 'bg-[#90CAF9]/5 border-[#90CAF9]' }, // { type: 'Valentine Coupons', code: 'VA-Day', validTill: 'Valid Till-Today 12 am', image: '/valentine.png', bgColor: 'bg-red-50', buttonColor: 'text-red-500 border-red-500' }, // { type: 'Black Friday Coupons', code: 'B-Day', validTill: 'Valid Till-Today 12 am', image: '/black-friday.png', bgColor: 'bg-gray-100', buttonColor: 'text-gray-700 border-gray-700' }, // { type: 'Birthday Coupons', code: 'B-Day', validTill: 'Valid Till-Today 12 am', image: '/birthday.png', bgColor: 'bg-yellow-50', buttonColor: 'text-yellow-600 border-yellow-600' }, // { type: 'Christmas Coupons', code: 'CH-Day', validTill: 'Valid Till-Today 12 am', image: '/christmas.png', bgColor: 'bg-green-50', buttonColor: 'text-green-600 border-green-600' }, // { type: 'Discount Coupons', code: 'DI34', validTill: 'Valid Till-Today 12 am', image: '/discount.png', bgColor: 'bg-purple-50', buttonColor: 'text-purple-600 border-purple-600' }, // { type: 'Eid Coupons', code: 'EI34', validTill: 'Valid Till-Today 12 am', image: '/eid.png', bgColor: 'bg-indigo-50', buttonColor: 'text-indigo-600 border-indigo-600' }, ];

    const CouponCard = ({ type, code, validTill, image, bgColor, buttonColor }) => { const [copied, setCopied] = useState(false);

    const handleCopy = () => {
        navigator.clipboard.writeText(code);
        setCopied(true);
        setTimeout(() => setCopied(false), 700);
    };
    
    return (
        <div className={`flex font-serif font-medium items-center p-6 mb-4 bg-[#F6F3F1]/30 shadow-md rounded-lg`}>
            <div className="flex-1">
                <p className="text-sm text-[#695C5C]">{type}</p>
                <h3 className="text-black font-sans text-2xl">{code}</h3>
                <p className="text-xs text-[#695C5C]">{validTill}</p>
                <button
                    onClick={handleCopy}
                    className={`mt-2 font-semibold px-7 py-1 text-sm ${buttonColor} border border-dashed rounded-lg transition-all duration-300 ease-in-out`}
                >
                    {copied ? 'Copied!' : 'Copy Code'}
                </button>
            </div>
            <div className="w-24 h-24 ml-4">
                <Image fill={true} src={image} alt={type} className="w-full h-full object-cover rounded-lg" />
            </div>
        </div>
    );
    

    };

    const MyCoupons = () => { const router = useRouter() return ( My Coupons {coupons.map((coupon, index) => ( <CouponCard key={index} {...coupon} /> ))} ); };

    export default MyCoupons;

    also find a solution for the colors... they should suit well with the image...

  2. Assistant

    To update your Next.js application to fetch coupon data from the https://api.naayiq.com/coupons API instead of using dummy data, you'll need to perform the following steps:

    1. Fetch Data on the Server Side: Use Next.js's server-side capabilities to fetch the data before rendering the page.
    2. Pass Data to the Client Component: Transfer the fetched data to the client-side MyCoupons component.
    3. Map API Data to UI Components: Transform the API data to match the props expected by your CouponCard component.
    4. Dynamic Coloring: Assign background and button colors based on the coupon type or other attributes to ensure they complement the associated images.

    Below is a comprehensive guide to implementing these changes.


    1. Update the CouponPage Component

    First, modify the CouponPage component to fetch data from the API on the server side. Since Next.js 13 with the App Router allows server components to fetch data directly, you can make the CouponPage component an asynchronous server component.

    pages/coupon/page.jsx

    // pages/coupon/page.jsx
    
    import MyCoupons from "@/components/Coupon";
    import Footer from "@/components/Footer";
    
    // Define a utility function to map coupon types to colors
    const getCouponColors = (couponType) => {
        const colorMap = {
            "Mother Day Coupons": {
                bgColor: 'bg-pink-50',
                buttonColor: 'bg-[#FF81AE]/5 border-[#FF81AE]',
            },
            "Free Delivery Coupons": {
                bgColor: 'bg-blue-50',
                buttonColor: 'bg-[#90CAF9]/5 border-[#90CAF9]',
            },
            // Add more mappings as needed
            // Default colors
            default: {
                bgColor: 'bg-gray-50',
                buttonColor: 'bg-gray-200 border-gray-400',
            },
        };
    
        return colorMap[couponType] || colorMap['default'];
    };
    
    export default async function CouponPage() {
        // Fetch data from the API
        const res = await fetch('https://api.naayiq.com/coupons', {
            // Optionally, add headers if needed
            headers: {
                'Content-Type': 'application/json',
            },
            // Revalidate the data every 60 seconds
            next: { revalidate: 60 },
        });
    
        // Handle errors
        if (!res.ok) {
            // You can handle errors more gracefully here
            throw new Error('Failed to fetch coupons');
        }
    
        const data = await res.json();
    
        // Map API data to match the props expected by CouponCard
        const coupons = data.map((coupon) => {
            // Determine the type based on the coupon name or other fields
            const type = coupon.name || "General Coupon";
    
            // Format the validTill date
            const validTill = new Date(coupon.end_date).toLocaleDateString(undefined, {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
            });
    
            // Construct the image path
            const image = `/images/coupons/${coupon.coupon_image}`; // Adjust the path as needed
    
            // Get colors based on the type
            const { bgColor, buttonColor } = getCouponColors(type);
    
            return {
                type,
                code: coupon.code,
                validTill: `Valid Till - ${validTill}`,
                image,
                bgColor,
                buttonColor,
            };
        });
    
        return (
            <main className="h-screen flex flex-col justify-between">
                <MyCoupons coupons={coupons} />
                <Footer />
            </main>
        );
    }
    

    Explanation:

    • Data Fetching: The fetch API is used to retrieve the coupons from https://api.naayiq.com/coupons. The next: { revalidate: 60 } option ensures that the data is revalidated every 60 seconds, which is useful for caching purposes.

    • Error Handling: If the API call fails, an error is thrown. You can customize this to display an error message to the user.

    • Data Mapping: The fetched data is transformed to match the props expected by the CouponCard component. This includes formatting dates and constructing image paths.

    • Dynamic Coloring: A utility function getCouponColors maps coupon types to specific background and button colors. You can expand the colorMap as needed to handle more coupon types.


    2. Update the MyCoupons Component

    Next, modify the MyCoupons component to accept the fetched data as props and render the coupons accordingly.

    components/Coupon.jsx

    'use client';
    
    import React, { useState } from 'react';
    import Image from "next/image";
    import { useRouter } from "next/navigation";
    import { CircleArrowLeft } from "lucide-react";
    import PropTypes from 'prop-types'; // Optional: For type checking
    
    // Remove dummy data
    
    const CouponCard = ({ type, code, validTill, image, bgColor, buttonColor }) => {
        const [copied, setCopied] = useState(false);
    
        const handleCopy = () => {
            navigator.clipboard.writeText(code);
            setCopied(true);
            setTimeout(() => setCopied(false), 700);
        };
    
        return (
            <div className={`flex font-serif font-medium items-center p-6 mb-4 ${bgColor} shadow-md rounded-lg`}>
                <div className="flex-1">
                    <p className="text-sm text-[#695C5C]">{type}</p>
                    <h3 className="text-black font-sans text-2xl">{code}</h3>
                    <p className="text-xs text-[#695C5C]">{validTill}</p>
                    <button
                        onClick={handleCopy}
                        className={`mt-2 font-semibold px-7 py-1 text-sm ${buttonColor} border border-dashed rounded-lg transition-all duration-300 ease-in-out`}
                    >
                        {copied ? 'Copied!' : 'Copy Code'}
                    </button>
                </div>
                <div className="w-24 h-24 ml-4 relative">
                    <Image
                        src={image}
                        alt={type}
                        fill
                        className="object-cover rounded-lg"
                    />
                </div>
            </div>
        );
    };
    
    CouponCard.propTypes = {
        type: PropTypes.string.isRequired,
        code: PropTypes.string.isRequired,
        validTill: PropTypes.string.isRequired,
        image: PropTypes.string.isRequired,
        bgColor: PropTypes.string.isRequired,
        buttonColor: PropTypes.string.isRequired,
    };
    
    const MyCoupons = ({ coupons }) => {
        const router = useRouter();
        return (
            <div className="bg-white min-h-screen p-6">
                <header className="flex items-center mb-6">
                    <CircleArrowLeft
                        size={52}
                        strokeWidth={0.7}
                        onClick={() => router.back()}
                        className="p-2 cursor-pointer relative z-20"
                    />
                    <h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">
                        My Coupons
                    </h1>
                </header>
                <div className="space-y-4">
                    {coupons.length > 0 ? (
                        coupons.map((coupon, index) => (
                            <CouponCard key={index} {...coupon} />
                        ))
                    ) : (
                        <p className="text-center text-gray-500">No coupons available.</p>
                    )}
                </div>
            </div>
        );
    };
    
    MyCoupons.propTypes = {
        coupons: PropTypes.arrayOf(
            PropTypes.shape({
                type: PropTypes.string.isRequired,
                code: PropTypes.string.isRequired,
                validTill: PropTypes.string.isRequired,
                image: PropTypes.string.isRequired,
                bgColor: PropTypes.string.isRequired,
                buttonColor: PropTypes.string.isRequired,
            })
        ).isRequired,
    };
    
    export default MyCoupons;
    

    Explanation:

    • Props Handling: The MyCoupons component now accepts a coupons prop, which is an array of coupon objects fetched from the API.

    • Conditional Rendering: If there are no coupons, a message is displayed to inform the user.

    • Styling Adjustments:

      • bgColor: Applied dynamically to the coupon card's background.
      • buttonColor: Applied dynamically to the "Copy Code" button.
    • Image Handling: Ensure that the image paths constructed in the CouponPage component (/images/coupons/${coupon.coupon_image}) correspond to the actual location of your images. Adjust the path as necessary.

    • Cursor Style: Added cursor-pointer to the back button for better UX.

    • PropTypes: Optional but recommended for type checking, ensuring that the components receive the correct props.


    3. Handle Dynamic Coloring Based on Coupon Attributes

    To ensure that the colors of the coupons suit their respective images or types, you can enhance the getCouponColors utility function. This function maps specific coupon types to predefined color schemes. You can expand this function based on the types returned by your API.

    Enhancing getCouponColors

    // Utility Function to Map Coupon Types to Colors
    const getCouponColors = (couponType) => {
        const colorMap = {
            "Mother Day Coupons": {
                bgColor: 'bg-pink-50',
                buttonColor: 'bg-[#FF81AE]/5 border-[#FF81AE]',
            },
            "Free Delivery Coupons": {
                bgColor: 'bg-blue-50',
                buttonColor: 'bg-[#90CAF9]/5 border-[#90CAF9]',
            },
            "Valentine Coupons": {
                bgColor: 'bg-red-50',
                buttonColor: 'bg-[#F44336]/5 border-[#F44336]',
            },
            "Black Friday Coupons": {
                bgColor: 'bg-gray-100',
                buttonColor: 'bg-[#757575]/5 border-[#757575]',
            },
            "Birthday Coupons": {
                bgColor: 'bg-yellow-50',
                buttonColor: 'bg-[#FFEB3B]/5 border-[#FFEB3B]',
            },
            "Christmas Coupons": {
                bgColor: 'bg-green-50',
                buttonColor: 'bg-[#4CAF50]/5 border-[#4CAF50]',
            },
            "Discount Coupons": {
                bgColor: 'bg-purple-50',
                buttonColor: 'bg-[#9C27B0]/5 border-[#9C27B0]',
            },
            "Eid Coupons": {
                bgColor: 'bg-indigo-50',
                buttonColor: 'bg-[#3F51B5]/5 border-[#3F51B5]',
            },
            // Add more mappings as per your coupon types
            // Default colors
            default: {
                bgColor: 'bg-gray-50',
                buttonColor: 'bg-gray-200 border-gray-400',
            },
        };
    
        return colorMap[couponType] || colorMap['default'];
    };
    

    Explanation:

    • Color Mapping: Each coupon type is associated with specific background and button colors that complement the associated images.

    • Default Colors: If a coupon type doesn't match any predefined type, default colors are applied to maintain consistency.

    • Customization: Feel free to adjust the colors to better match your application's theme and the specific images used.


    4. Ensure Image Accessibility

    Make sure that the images referenced (coupon.coupon_image) are stored in the /public/images/coupons/ directory or adjust the image path accordingly in the CouponPage component.

    Example Directory Structure

    /public
        /images
            /coupons
                2079.webp
                2119.jpeg
                // Add other images here
    

    Alternative Image Sources

    If your images are hosted externally, adjust the image URL accordingly. For example:

    const image = `https://api.naayiq.com/images/coupons/${coupon.coupon_image}`;
    

    Ensure that the next.config.js includes the external domains if you use Next.js's Image Optimization.


    5. Final Folder Structure and Files

    Ensure your project has the following structure for clarity:

    /components
        Coupon.jsx
    /pages
        /coupon
            page.jsx
    /public
        /images
            /coupons
                mom.png
                car.png
                2079.webp
                2119.jpeg
                // ... other images
    

    6. Testing the Implementation

    After making these changes, test your application to ensure:

    • Coupons are fetched correctly from the API.
    • Coupons are displayed with appropriate images and colors.
    • The "Copy Code" button functions as expected.
    • The back button navigates correctly.
    • Responsiveness and styling are consistent across different devices.

    7. Handling Edge Cases and Enhancements

    Empty State Handling

    If the API returns an empty array, the user should see a friendly message indicating that there are no available coupons.

    {coupons.length > 0 ? (
        coupons.map((coupon, index) => (
            <CouponCard key={index} {...coupon} />
        ))
    ) : (
        <p className="text-center text-gray-500">No coupons available.</p>
    )}
    

    Loading State

    While the data is being fetched, consider displaying a loading indicator to enhance user experience.

    // In CouponPage component
    // Next.js automatically handles loading states for server components, but for client components, you might need to handle it manually.
    

    Error Handling

    Implement more sophisticated error handling to provide feedback to users in case of API failures.

    // In CouponPage component
    try {
        const res = await fetch('https://api.naayiq.com/coupons', { /* options */ });
        if (!res.ok) throw new Error('Failed to fetch');
        // ... rest of the code
    } catch (error) {
        return (
            <div className="flex flex-col items-center justify-center min-h-screen">
                <p className="text-red-500">Failed to load coupons. Please try again later.</p>
            </div>
        );
    }
    

    8. Complete Code Snippets

    pages/coupon/page.jsx

    import MyCoupons from "@/components/Coupon";
    import Footer from "@/components/Footer";
    
    // Utility Function to Map Coupon Types to Colors
    const getCouponColors = (couponType) => {
        const colorMap = {
            "Mother Day Coupons": {
                bgColor: 'bg-pink-50',
                buttonColor: 'bg-[#FF81AE]/5 border-[#FF81AE]',
            },
            "Free Delivery Coupons": {
                bgColor: 'bg-blue-50',
                buttonColor: 'bg-[#90CAF9]/5 border-[#90CAF9]',
            },
            // Add more mappings as needed
            default: {
                bgColor: 'bg-gray-50',
                buttonColor: 'bg-gray-200 border-gray-400',
            },
        };
    
        return colorMap[couponType] || colorMap['default'];
    };
    
    export default async function CouponPage() {
        try {
            const res = await fetch('https://api.naayiq.com/coupons', {
                headers: {
                    'Content-Type': 'application/json',
                },
                next: { revalidate: 60 },
            });
    
            if (!res.ok) {
                throw new Error('Failed to fetch coupons');
            }
    
            const data = await res.json();
    
            const coupons = data.map((coupon) => {
                const type = coupon.name || "General Coupon";
                const validTill = new Date(coupon.end_date).toLocaleDateString(undefined, {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                });
                const image = `/images/coupons/${coupon.coupon_image}`; // Adjust the path as needed
                const { bgColor, buttonColor } = getCouponColors(type);
    
                return {
                    type,
                    code: coupon.code,
                    validTill: `Valid Till - ${validTill}`,
                    image,
                    bgColor,
                    buttonColor,
                };
            });
    
            return (
                <main className="h-screen flex flex-col justify-between">
                    <MyCoupons coupons={coupons} />
                    <Footer />
                </main>
            );
        } catch (error) {
            // Handle the error gracefully
            return (
                <div className="flex flex-col items-center justify-center min-h-screen">
                    <p className="text-red-500">Failed to load coupons. Please try again later.</p>
                </div>
            );
        }
    }
    

    components/Coupon.jsx

    'use client';
    
    import React, { useState } from 'react';
    import Image from "next/image";
    import { useRouter } from "next/navigation";
    import { CircleArrowLeft } from "lucide-react";
    import PropTypes from 'prop-types';
    
    const CouponCard = ({ type, code, validTill, image, bgColor, buttonColor }) => {
        const [copied, setCopied] = useState(false);
    
        const handleCopy = () => {
            navigator.clipboard.writeText(code);
            setCopied(true);
            setTimeout(() => setCopied(false), 700);
        };
    
        return (
            <div className={`flex font-serif font-medium items-center p-6 mb-4 ${bgColor} shadow-md rounded-lg`}>
                <div className="flex-1">
                    <p className="text-sm text-[#695C5C]">{type}</p>
                    <h3 className="text-black font-sans text-2xl">{code}</h3>
                    <p className="text-xs text-[#695C5C]">{validTill}</p>
                    <button
                        onClick={handleCopy}
                        className={`mt-2 font-semibold px-7 py-1 text-sm ${buttonColor} border border-dashed rounded-lg transition-all duration-300 ease-in-out`}
                    >
                        {copied ? 'Copied!' : 'Copy Code'}
                    </button>
                </div>
                <div className="w-24 h-24 ml-4 relative">
                    <Image
                        src={image}
                        alt={type}
                        fill
                        className="object-cover rounded-lg"
                    />
                </div>
            </div>
        );
    };
    
    CouponCard.propTypes = {
        type: PropTypes.string.isRequired,
        code: PropTypes.string.isRequired,
        validTill: PropTypes.string.isRequired,
        image: PropTypes.string.isRequired,
        bgColor: PropTypes.string.isRequired,
        buttonColor: PropTypes.string.isRequired,
    };
    
    const MyCoupons = ({ coupons }) => {
        const router = useRouter();
        return (
            <div className="bg-white min-h-screen p-6">
                <header className="flex items-center mb-6">
                    <CircleArrowLeft
                        size={52}
                        strokeWidth={0.7}
                        onClick={() => router.back()}
                        className="p-2 cursor-pointer relative z-20"
                    />
                    <h1 className="text-3xl z-10 text-[#181717] left-0 right-0 absolute font-sans text-center font-medium">
                        My Coupons
                    </h1>
                </header>
                <div className="space-y-4">
                    {coupons.length > 0 ? (
                        coupons.map((coupon, index) => (
                            <CouponCard key={index} {...coupon} />
                        ))
                    ) : (
                        <p className="text-center text-gray-500">No coupons available.</p>
                    )}
                </div>
            </div>
        );
    };
    
    MyCoupons.propTypes = {
        coupons: PropTypes.arrayOf(
            PropTypes.shape({
                type: PropTypes.string.isRequired,
                code: PropTypes.string.isRequired,
                validTill: PropTypes.string.isRequired,
                image: PropTypes.string.isRequired,
                bgColor: PropTypes.string.isRequired,
                buttonColor: PropTypes.string.isRequired,
            })
        ).isRequired,
    };
    
    export default MyCoupons;
    

    9. Conclusion

    By implementing the above changes, your Next.js application will dynamically fetch coupon data from the specified API, render them using client-side components, and apply styles that complement each coupon's image. This approach enhances scalability, maintainability, and user experience.

    Feel free to further customize the components, add more styles, or handle additional coupon attributes as needed.