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;
}
}
}