zodios-react icon indicating copy to clipboard operation
zodios-react copied to clipboard

Type error when destructuring from hooks

Open nerdstep opened this issue 2 years ago • 0 comments

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.

  1. Bind the this context to the method in the constructor:
class Hooks {
    constructor() {
        this.useInfiniteQuery = this.useInfiniteQuery.bind(this);
    }
    useInfiniteQuery = function() {
        console.log(this);
    }
}
  1. Use an arrow function to define the method:
class Hooks {
    useInfiniteQuery = () => {
        console.log(this);
    }
}

nerdstep avatar May 31 '23 18:05 nerdstep