reactive/data-client

Example custom GET URL in documentation doesn't work

Closed this issue · 0 comments

ah19 commented

React version (e.g., 17.0.2)
18.2.0

Package manager version (e.g., yarn 2, npm 8)
8.1.2

Node version (e.g., 16.13.2)
16.13.1

Rest Hooks version (e.g., 6.2.0)
6.3.6

Describe the bug
The custom get example does not work as intended. The URL called is the url() from the resource rather than the custom one defined alongside. The usage example is also incorrect as it provides a parameter to the useSuspense call, but the overridden fetch() doesn't take any parameters.

I couldn't find any examples of how to override fetch properly in the docs. I got it working with:

  static current<T extends typeof Resource>(this: T): RestEndpoint<
  (this: RestEndpoint) => Promise<any>,
  SchemaDetail<AbstractInstanceType<T>>,
  undefined
> {
    const urlRoot = this.urlRoot;
    const endpoint = this.detail();
    const instanceFetch = this.fetch.bind(this);
    return endpoint.extend({
      fetch() {
        return instanceFetch(
          this.url(),
          (this as any).getFetchInit(),
        );
      },
      url() {
        return `${urlRoot}/current_user`;
      },
    });
  }

To Reproduce

import { Resource } from '@rest-hooks/rest';

export default class UserResource extends Resource {
  readonly id: string | undefined = undefined;
  readonly email: string = '';

  pk() {
    return this.id;
  }

  /** Retrieves current logged in user */
  static current<T extends typeof Resource>(this: T) {
    const endpoint = this.detail();
    return endpoint.extend({
      fetch() { return endpoint(this); },
      url() { return '/current_user/' }
    })
  }

  static urlRoot = "/api/v1/user";
}

Calling the above with useSuspense(UserResource.currentUser()); will call "/api/v1/user/" rather than "/current_user/"

Expected behavior
Example from the docs works.