reactive / data-client

Async State Management without the Management. REST, GraphQL, SSE, Websockets
https://dataclient.io
Apache License 2.0
1.94k stars 93 forks source link

React Hook cannot be called in a class component. #2561

Closed jb41997 closed 1 year ago

jb41997 commented 1 year ago

React version (React version (18.2.0)

**TypeScript version (5.0.3)

Rest Hooks version (latest)

Describe the bug I'm trying to implement a similar authentication check as the Github Demo uses. See the base.ts.

export class GithubEndpoint<
  O extends RestGenerics = any,
> extends RestEndpoint<O> {
  urlPrefix = HOST;

  getRequestInit(body: any): RequestInit {
    let init: RequestInit;
    if (body) {
      init = super.getRequestInit(deeplyApplyKeyTransform(body, snakeCase));
    }
    init = super.getRequestInit(body);
    if (getAuth()) {
      init.mode = 'cors';
      init.headers = {
        ...init.headers,
        Authorization: 'Basic ' + getAuth(),
      };
    }
    return init;
  }

However, getAuth() is a react hook and cannot be called in a class component. At least that is the error I'm receiving. Does anyone have a a good example of how to accomplish this or something similar? How to inherit check auth on every endpoint/resource?

ntucker commented 1 year ago

getAuth is definitely not a hook - https://stackblitz.com/github/reactive/data-client/tree/master/examples/github-app?file=src%2Fresources%2FAuth.ts It doesn't call any other hooks and isn't prefixed with 'use'.

However, useSuspense() is definitely a hook, so if you want to use that you can follow this guide to using any hook with a class component!

Feel free to pace your stack trace if this is wrong though!

jb41997 commented 1 year ago

@ntucker I really appreciate the pointer.