Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

html - How can I loop through Nuxt.js generate routes to allow all my pages to render while using Woocommerce API?

Hello and thanks for the help in advance.

I'm trying to get my Nuxt app to automatically loop through my Woocommerce API automatically so it can generate the pages without much work.

How do I get the loop to function. Right now, I'm having issues and get a Nuxt Fatal Error:

TypeError: Cannot read property 'forEach' of undefined

Screenshot of Error + Code

I'm using Woocommerce API and, as you can see in the screenshot above, the Woocommerce code is imported into this code I need help with using a standard import.

import WooCommerce from './woocommerce.js';

   generate: {
      routes() {
        WooCommerce.get("products").then((response) => {
          let totalPages = response.headers['x-wp-totalpages'];
          let page = 1;
          while(page <= totalPages) {
            WooCommerce.get("products", page).then((response) => {
              response.data.map(product => {
                return '/product/' + product.slug
              });
            })
            page++;
          }
        })
      }
    },

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not returning any routes in your routes function. Because of that, nuxt fails as it tries to iterate over them in a later step.

Assuming your way of accessing your API is correct, you would only need to add an array to which you push your routes and then return it.

I'm usually using async/await, which is why my code looks slightly different. It is a bit easier in this case I think.

// Declare the routes function asynchronous
async routes() {
  const productsResponse = await WooCommerce.get('products');
  const totalPages = productsResponse.headers['x-wp-totalpages'];

  // Add an array to collect your routes
  const routes = [];

  let page = 1;
  while (page <= totalPages) {
    const pagesResponse = await WooCommerce.get('products', page);

    // The 'map' function returns the routes for this set of pages
    const productRoutes = pagesResponse.data.map((product) => {
      return '/product/' + product.slug;
    });

    // Push your routes to the created array-
    routes.push(...productRoutes);

    page++;
  }

  // Return your routes
  return routes;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...