skip to Main Content

I need to create some cards that will have the content based on data returned from an API. However, I haven’t found ways to do this when the website is being rendered, and the ones I’ve tried haven’t worked. The div will contain the cards, but how can i pass the "packages" as properties to the component?

import { GetPackages, SetWebstoreIdentifier } from "tebex_headless";
SetWebstoreIdentifier("tv5y-6b682b0fe1661c45c836b56fb7244d3d840d18c7");

async function test() {
  const packages = await GetPackages();
  console.log(packages[0]);
}
test();
export function CardBox() {
  return (
    <div
      className="
      grid gap-6 place-items-center
      sm:grid-cols-2
      lgg:grid-cols-4
    "
    ></div>
  );
}

I tried to use an

{Array.from({length:4}).map(() => { <Card //The values returned from the package would come here /> })}

but, in the ways I’ve tried, I couldn’t pass the package values into the component.

2

Answers


  1. The steps that you need to do:

    1. State Initialization.
    2. Data Fetching with useEffect.
    3. Updating State.
    4. Dynamic Rendering.

    Let’s imagine that this the data returned from your API. And let’s call it packageData.

    [
      {
        "id": "1",
        "name": "Basic Package",
        "description": "This is a basic package offering essential features.",
        "price": "10.00"
      },
      {
        "id": "2",
        "name": "Premium Package",
        "description": "This package includes all premium features for advanced users.",
        "price": "50.00"
      },
      {
        "id": "3",
        "name": "Pro Package",
        "description": "The pro package offers professional-grade features for experts.",
        "price": "100.00"
      }
    ]
    

    Here is the edited version of CardBox:

    import React, { useState, useEffect } from 'react';
    import { GetPackages, SetWebstoreIdentifier } from "tebex_headless";
    // Assuming you have a Card component that accepts package data as props
    import Card from './Card';
    
    // Set your webstore identifier outside of the component to avoid setting it on every render
    SetWebstoreIdentifier("tv5y-6b682b0fe1661c45c836b56fb7244d3d840d18c7");
    
    export function CardBox() {
      // Initialize state to hold your packages
      const [packages, setPackages] = useState([]);
    
      useEffect(() => {
        // Define an async function to fetch your packages
        async function fetchPackages() {
          try {
            const packagesData = await GetPackages();
            // Update state with the fetched packages
            setPackages(packagesData);
          } catch (error) {
            console.error("Failed to fetch packages:", error);
          }
        }
    
        // Call the fetch function
        fetchPackages();
      }, []); // Empty dependency array means this effect runs once after the initial render
    
      return (
        <div className="grid gap-6 place-items-center sm:grid-cols-2 lgg:grid-cols-4">
          {packages.map((packageData) => (
            // Render a Card for each package, passing the package data as props
            <Card key={packageData.id} packageData={packageData} />
          ))}
        </div>
      );
    }
    

    And here is how you’ll create your Card component. You can edit it according to the data coming from your API.

    Card component:

    import React from 'react';
    function Card({ packageData }) {
      // Destructure the needed properties from packageData
      const { name, description, price } = packageData;
    
      return (
        <div className="card">
          <div className="card-header">
            <h2>{name}</h2> {/* Display the package name */}
          </div>
          <div className="card-body">
            <p>{description}</p> {/* Display the package description */}
          </div>
          <div className="card-footer">
            <p>Price: ${price}</p> {/* Display the package price */}
          </div>
        </div>
      );
    }
    
    export default Card;
    
    Login or Signup to reply.
  2. In Next.js (App Router) you can create async component (only works with server components i.e. not using "use client").

    so you can fetch your data directly in your component then render it as you like.

    (the below code assumes that const packages = await GetPackages(); will return data in array-like format)

    import { GetPackages, SetWebstoreIdentifier } from "tebex_headless";
    SetWebstoreIdentifier("tv5y-6b682b0fe1661c45c836b56fb7244d3d840d18c7");
    
    export default async function CardBox() {
      const packages = await GetPackages();
      // parse your data if needed
      const data = await packages.json();
      console.log(data) // check your data your data
      return (
        {data.map(item => (
        <div
          key={item.id}
          className="
          grid gap-6 place-items-center
          sm:grid-cols-2
          lgg:grid-cols-4">
        {item?.name}
        </div>))}
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search