I'm getting an error about uncaught products in a collection - can you help me understand what this means and how to

My next.js website, which fetches products from Shopify, was working flawlessly until a few months ago when it suddenly stopped building on the development server.

Now, whenever I try to run the website locally, I am encountering a "Cannot read properties of undefined" error, causing the page to not load at all.

What are the potential reasons behind this issue and what steps should I take to resolve it?

error - lib/shopify.js (353:31) @ getProductsInCollection
TypeError: Cannot read properties of undefined (reading 'collectionByHandle')
  351 |       const cursor = response.data.products.edges[num - 1].cursor;
  352 | 
> 353 |       return data.concat(await recursiveCatalog(cursor));
      |                               ^
  354 |     } else {
  355 |       return data;
  356 |     }

This is how the data is fetched from Shopify:

    const domain = process.env.SHOPIFY_STORE_DOMAIN
    const storefrontAccessToken = process.env.SHOPIFY_STOREFRONT_ACCESSTOKEN
    
    async function ShopifyData(query) {
      const URL = `https://${domain}/api/2021-07/graphql.json`
    
      const options = {
        endpoint: URL,
        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(URL, options).then(response => {
          return response.json()
        })
    
        return data
      } catch (error) {
        throw new Error("Products not fetched")
      }
    }

The error appears to be related to fetching products from a specific collection.

export async function getProductsInCollection() {
  const query = `
  {
    collectionByHandle(handle: "frontpage") {
      title
      products(first: 60) {
        edges {
          node {
            id
            title
            productType
            handle
            metafields(first: 2) {
              edges {
                  node {
                      namespace
                      key
                      value
                  }
              }
          }
        }
      }
    }
  }`
  const response = await ShopifyData(query);
  const allProducts = response.data.collectionByHandle.products.edges
    ? response.data.collectionByHandle.products.edges
    : [];
  return allProducts;
}
export async function recursiveCatalog(cursor = '', initialRequest = true) {
  let data;

  if (cursor !== '') {
    const query = `{
      products(after: "${cursor}", first: 250) {
        edges {
          cursor
          node {
            id
            handle
          }
        }
        pageInfo {
          hasNextPage
        }
      }
    }`;

    const response = await ShopifyData(query);
    data = response.data.products.edges ? response.data.products.edges : [];

    if (response.data.products.pageInfo.hasNextPage) {
      const num = response.data.products.edges.length;
      const cursor = response.data.products.edges[num - 1].cursor;
      console.log('Cursor: ', cursor);

      return data.concat(await recursiveCatalog(cursor));
    } else {
      return data;
    }
  } else {
    const query = `{
      products(first: 250) {
        edges {
          cursor
          node {
            id
            handle
          }
        }
        pageInfo {
          hasNextPage
        }
      }
    }
    `;

    const response = await ShopifyData(query);
    data = response.data.products.edges ? response.data.products.edges : [];

    if (response.data.products.pageInfo.hasNextPage) {
      const num = response.data.products.edges.length;
      const cursor = response.data.products.edges[num - 1].cursor;

      return data.concat(await recursiveCatalog(cursor));
    } else {
      return data;
    }
  }
}

Answer №1

One important thing to note is that the function collectionByHandle has been deprecated and should now be replaced with collection.

It's recommended to add a guard clause when using the fetch API or Shopify API to handle error responses.

    if (!response.ok) { 
        console.error('Error occurred while fetching data') 
    } 

This will provide some insight into how the data retrieval process is proceeding.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Ensure the http request is finished before loading the template

When my template loads first, the http request is fired. Because of this, when I load the page for the first time, it shows a 404 image src not found error in the console. However, after a few milliseconds, the data successfully loads. After researching a ...

Innovative concepts for designing web applications

Here's a unique situation that requires some brainstorming. I'm looking for any advice or suggestions. Imagine a tennis court equipped with sensors throughout - the net, lines, everything has sensors built in. These sensors are constantly sending ...

The error "Cannot set headers after they are sent" is causing issues with the functionality of the Express session

Ensuring secure authentication for my Node.js application is a top priority. I have implemented the use of express-session npm to achieve this goal. The idea is that upon successful login on the /login page, a session should be initiated and the user shoul ...

Implementing asynchronous file reading with module.exports in Node.js

Apologies in advance for what may seem like a basic question, but I'm delving into the inner workings of node and need help with a particular issue: I am trying to send an object or file from fs.readFile using require and module.exports. So far, this ...

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

Expanding box geometry from a single side in Three.js

Just starting out with three.js and my first task was to create a box geometry that could be increased from only one side. Issue : When increasing the width or height of an object, both sides automatically expand. Check out this jsFiddle Example I waste ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

In JavaScript, using window["functionName"](arguments) will result in a TypeError message saying that the function does not exist

When trying to execute an AJAX function based on the active tab in my application, everything works smoothly when I trigger the function after specific events. However, I encounter difficulties when attempting to call the function using a dynamically gener ...

Guide on automatically extracting table rows and generating an Excel spreadsheet

I am currently working on a script that dynamically adds the first row (TH) to a table and then exports it to an Excel sheet. However, I am facing an issue where instead of appending each row, the script keeps stacking on top of the next table row. Below ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

Top tip: Utilize jQuery for the most effective method of adding content to the HTML of a paragraph situated

One interesting challenge I'm facing involves a textarea that stores dynamic HTML content within paragraph (p) tags. Initial HTML: <textarea rows='7' class='form-control' id='comments'><p>My variable HTM ...

Can the document.ready function and a button click function be merged together effectively?

I am working on a tavern name generator that generates names when the document loads and also when a button is clicked. Is it possible to combine the document.ready function with the button click function like this: $(document).ready(function(){ ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Node.js project is set up globally on personal system

Introduction I'm diving into the world of Node.js and eager to learn. NPM has been a game changer for me as I can easily install packages globally and utilize them as standalone applications accessible from anywhere on my system. To my surprise, thi ...

guaranteed function to retrieve React elements

Is there a solution for the issue where if-else doesn't work in run build but works in run dev? The only way I've found to make it work is by using a react hook, but I'm unsure which one to use and where to implement it. import { useAdd ...

`How to resolve `next dev` ESM import issues?`

Upon running next dev on my project, I encountered a series of errors. These errors stem from an internal library that serves as a dependency for other internal libraries: Module not found: ESM packages (@company/style-lib) need to be imported. Use 'i ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

Unable to leverage vscode workspace path for the next js 13 project

I am facing an issue with TypeScript despite having the latest versions installed in my project (TypeScript 5.2.2 and @types/react 18.2.21): Next 13 — client and async server component combined: 'Promise<Element>' is not a valid JSX elem ...