Development discussions around Shopify APIs
Hello - I'm currently attempting to create code that would allow me to paginate through search results from the following base graphQL query:
static func searchForProducts(searchString:String, after cursor: String? = nil) -> Storefront.QueryRootQuery {
Storefront.buildQuery { $0
.shop { $0
.products(first:20, after:cursor, query: searchString) { $0
.fragmentForStandardProduct()
}
}
}
}
Once pagination has been called, the following code is executed:
func collectionViewWillBeginPaging(_ collectionView: StorefrontCollectionView) {
if let products = self.products,
let lastProduct = products.items.last {
Client.shared.searchProducts(searchString: processedString, after: lastProduct.cursor) { (products) in
if let products = products {
self.products.appendPage(from: products)
self.collectionView.completePaging()
self.collectionView.reloadData()
}
}
}
}
Here is the code for searchProducts()
@discardableResult
func searchProducts(searchString:String, after cursor: String? = nil, completion: @escaping (PageableArray<ProductViewModel>?) -> Void) -> Task {
let query = ClientQuery.searchForProducts(searchString: searchString, sortKey: sortKey)
let task = self.client.queryGraphWith(query) { (query, error) in
error.debugPrint()
if let query = query {
let products = PageableArray(
with: query.shop.products.edges,
pageInfo: query.shop.products.pageInfo
)
completion(products)
} else {
print("Failed to load products")
completion(nil)
}
}
task.resume()
return task
}
The above code is calling pagination, but instead of querying the products after .lastProduct, it simply starts the search back at the beginning. The result is an infiniately paginated product list that loops through the same 20 products over and over.
So obviously there is a flaw in my logic. I tried to apply the same pagination code that was found in the SDK for paginating through a collection, which is not working.
Any ideas? Thanks.
Your call to "ClientQuery.searchForProducts" is missing the "cursor" parameter. Your search is requesting the same page of products, over and over again.
Nice catch Dima! Thanks a ton!
I would have stared at that for 10 more hours and not found the issue.
Alex
As a business owner, have you ever wondered when your customer's first impression of yo...
By Skye Jun 6, 2023We're excited to announce improvements to the threaded messaging experience in our communi...
By TyW May 31, 2023Thank you to everyone who participated in our AMA with Klaviyo. It was great to see so man...
By Jacqui May 30, 2023