lwc icon indicating copy to clipboard operation
lwc copied to clipboard

Document Custom Wire Method Implementaion more clearly

Open DougMidgley opened this issue 2 years ago • 2 comments

Is your feature request related to a problem? Please describe. I am trying to implement a custom wire method in LWC OSS, but using the format in wire-reform (0000-wire-reform), there doesn't seem to be any documentation on how to make the wire method ALSO imperatively callable (as you would expect from Apex Methods).

simple calling the custom wire class doesnt work, as you cannot call a class directly. I am unsure if there is another way around this.

Describe the solution you'd like a clear code example of how a wire method can be implemented, but also work with imperative calls like in apex.

Describe alternatives you've considered simply not implementing wire methods and managing lifecycle directly.

Additional context there is a couple of examples which show wire methods implemented in OSS but only provide the @wire variant

  • https://github.com/surajp/lwc-oss-wire
  • https://github.com/pmdartus/rcast

https://github.com/salesforce/lwc-rfcs/blob/master/text/0000-wire-reform.md explicitly mentions that this should be possible but does not provide clear examples

DougMidgley avatar Sep 18 '22 19:09 DougMidgley

FYI @jodarove

nolanlawson avatar Sep 19 '22 18:09 nolanlawson

Hi @DougMidgley, it is true there's not much documentation on how to make a wire adapter also callable. you can find how to do it in the wire-reform rfc, specifically in the adoption strategy section.

On top of the resources you mentioned, there's also the lwc documentation, although you won't find the example you want. while we add it, here is one for you to use:

class GetBooksAdapter {
    constructor(dataCallback) {
        this.dataCallback = dataCallback;
        this.dataCallback();
    }

    connect() {
        getBooksInstances.add(this);
    }

    disconnect() {
        getBooksInstances.remove(this);
    }

    update() {
        this._refresh();
    }

    _refresh() {
        const allBooks = bookEndpoint.getAll();
        this.dataCallback(allBooks);
    };
}

function getBooks() {
  return bookEndpoint.getAll();
}

Object.freeze(GetBooksAdapter);
Object.freeze(GetBooksAdapter.prototype);

Object.defineProperty(getBooks, 'adapter', {
        writable: false,
        configurable: false,
        value: GetBooksAdapter,
    });

export { getBooks };

jodarove avatar Sep 20 '22 14:09 jodarove