异步等待直到刷新后才收到响应

问题描述 投票:0回答:1

我想使用异步等待从 API 获取数据。我有一个文件,其中包含 API 调用方法,另一个文件包含我想要将数据渲染到组件中的文件。我很难理解异步等待的工作原理。当我第一次运行页面并加载产品页面时,在按下刷新之前,我没有从 getAllProductsInCollection 函数得到任何响应。我认为这是因为其余代码在 API 收到任何实际响应之前就已执行,一旦 API 获取数据并刷新,它就有数据传递到组件中。

APICallsJS

async function callShopify(query) {
  const fetchUrl = `https://${domain}/api/2023-04/graphql.json`;

  const fetchOptions = {
    endpoint: fetchUrl,
    method: "POST",
    headers: {
      "X-Shopify-Storefront-Access-Token": storefrontAccessToken,
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query }),
  };

  try {
    const data = await fetch(fetchUrl, fetchOptions, { cache: 'no-store' }).then((response) =>
      response.json(),
    );
    return data;
  } catch (error) {
    throw new Error("Could not fetch products!");
  }
}

export async function getAllProductsInCollection(collection) {
  const query =
    `{
      collectionByHandle(handle: "${collection}") {
        id
        title
        products(first: 250) {
          edges {
            node {
              id
              title
              description
              handle
              images(first: 250) {
                edges {
                  node {
                    id
                    originalSrc
                    height
                    width     
                    altText             
                  }
                }
              }
              variants(first: 250) {
                edges {
                  node {
                    id
                    title
                    price  {
                        amount
                    }              
                  }
                }
              }
            }
          }
        }
      }
    }`
  ;

  const response = await callShopify(query);

  const allProducts = response.data.collectionByHandle.products.edges
    ? response.data.collectionByHandle.products.edges
    : [];

    console.log("inside shopify call: "+ allProducts)
  return allProducts;
}

产品页面

export default async function Page() {

  const tmp = await getAllProductsInCollection("test")
  const products = JSON.parse(JSON.stringify(tmp))
  
  return (
    <div>
      <ProductListings products={products} />
    </div>
  )
}

我尝试在 API 部分中控制台记录数据,但什么也没得到。我已通过控制台记录了 productsjs 页面中的数据,并且我得到“[]”,这意味着尚未从 API 调用接收到数据。

javascript next.js async-await shopify nextjs14
1个回答
0
投票

为您的 API 响应添加多项检查以调试错误,并验证您端是否正确进行了 api 调用,我做了一些更改,这将使您可以轻松调试错误。只需执行以下代码即可。

const domain = 'your-shopify-domain';
const storefrontAccessToken = 'your-storefront-access-token';

async function callShopify(query) {
  const fetchUrl = `https://${domain}/api/2023-04/graphql.json`;

  const fetchOptions = {
    method: "POST",
    headers: {
      "X-Shopify-Storefront-Access-Token": storefrontAccessToken,
      "Accept": "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ query }),
  };

  try {
    const response = await fetch(fetchUrl, fetchOptions);
    const data = await response.json();
    
    if (!response.ok) {
      console.error("Failed to fetch data from Shopify:", data);
      throw new Error(data.errors ? data.errors[0].message : "Unknown error");
    }
    
    return data;
  } catch (error) {
    console.error("Could not fetch products:", error);
    throw new Error("Could not fetch products!");
  }
}

export async function getAllProductsInCollection(collection) {
  const query = `{
    collectionByHandle(handle: "${collection}") {
      id
      title
      products(first: 250) {
        edges {
          node {
            id
            title
            description
            handle
            images(first: 250) {
              edges {
                node {
                  id
                  originalSrc
                  height
                  width     
                  altText             
                }
              }
            }
            variants(first: 250) {
              edges {
                node {
                  id
                  title
                  price  {
                      amount
                  }              
                }
              }
            }
          }
        }
      }
    }
  }`;

  const response = await callShopify(query);

  if (!response || !response.data || !response.data.collectionByHandle) {
    console.error("Invalid response structure:", response);
    return [];
  }

  const allProducts = response.data.collectionByHandle.products.edges || [];
  console.log("Fetched products:", allProducts);
  return allProducts;
}

产品页面.js

import { getAllProductsInCollection } from './APICalls';

export default async function Page() {
  let products = [];

  try {
    const tmp = await getAllProductsInCollection("test");
    products = JSON.parse(JSON.stringify(tmp));
  } catch (error) {
    console.error("Failed to fetch products on page load:", error);
  }

  return (
    <div>
      <ProductListings products={products} />
    </div>
  );
}

让我知道它是否有效!

© www.soinside.com 2019 - 2024. All rights reserved.