zodios-react
zodios-react copied to clipboard
Type error when destructuring from hooks
I ran into a somewhat unexpected issue -- when destructuring useInfiniteQuery from hooks a type error is thrown:
Cannot read properties of undefined (reading 'apiName')
Minimal example:
const hooks = new ZodiosHooks('jsonplaceholder', api)
const { useInfiniteQuery } = hooks
const Component = () => {
const { data, fetchNextPage } = useInfiniteQuery(...)
}
Repro: https://codesandbox.io/s/zodios-infinite-query-issue-lo5nlb?file=/src/Data.tsx
It took me a moment to realize that I was destructuring a class method, hence why the this context of the class was undefined, causing the error to be thrown.
So obviously rewriting the call as hooks.useInfiniteQuery() works as expected.
I think there are a couple of ways that the code could be modified to ensure that the context exists when used in this manner.
- Bind the
thiscontext to the method in the constructor:
class Hooks {
constructor() {
this.useInfiniteQuery = this.useInfiniteQuery.bind(this);
}
useInfiniteQuery = function() {
console.log(this);
}
}
- Use an arrow function to define the method:
class Hooks {
useInfiniteQuery = () => {
console.log(this);
}
}