Hooks in an API route handler #1869
-
Hi there, I'm wondering if the community can offer me some ideas for how I might resolve an "inavlid hook" issue within an API route handler. I have page that displays products in a grid. I want the products to be paginated in an infinite scroll. I have modeled this page after the My trouble lies in getting the
I understand that this error comes from React, not necessarily from Hydrogen. But I don't totally understand why I'm getting this error. I suppose it's because the For now, I have solved it by rewriting my hook's functionality inside the If anyone has insights as to how I might get this working, I would be very appreciative! For reference, here is a very simple reproduction: https://github.com/tylerpaige/hydrogen-api-route-hooks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @tylerpaige, thanks for the excellent write up. As you mentioned, API functions are not react components. Think of them like a regular lambda function. My advise is to modify your custom hook, so that the fetching logic is isolated from the hook logic. This way you end up with a utility and a hook — e.g This approach should help make testing easier and let you import We do this in our internals with |
Beta Was this translation helpful? Give feedback.
Hi @tylerpaige, thanks for the excellent write up.
As you mentioned, API functions are not react components. Think of them like a regular lambda function.
My advise is to modify your custom hook, so that the fetching logic is isolated from the hook logic. This way you end up with a utility and a hook — e.g
fetchProduct
anduseProduct
which usesfetchProduct
internally.This approach should help make testing easier and let you import
fetchProduct
inside the API route.We do this in our internals with
useShopQuery
andqueryShop
(which gets passed as a param to the api handler)