Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type error when destructuring from hooks #356

Open
nerdstep opened this issue May 31, 2023 · 0 comments
Open

Type error when destructuring from hooks #356

nerdstep opened this issue May 31, 2023 · 0 comments

Comments

@nerdstep
Copy link

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);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant