1 | # Wire Service
|
2 |
|
3 | This code is the implementation of the Lightning Web Component wire service. The wire service enables declarative binding of data providers called _wire adapters_ to a Lightning web component using the `@wire` decorator. It fulfills the goals of the [data service proposal](https://github.com/salesforce/lwc-rfcs/blob/master/text/0000-data-service.md).
|
4 |
|
5 | ## Summary
|
6 |
|
7 | Wire adapters simply provide data. A wire adapter doesn't know anything about the components that it provides data to.
|
8 |
|
9 | In a component, declare its data needs by using the `@wire` decorator to connect (or wire) it to a wire adapter. In this example, the component is wired to the `getBook` wire adapter. This declarative technique makes component code easy to read and reason about.
|
10 |
|
11 | ```js
|
12 | // bookItem.js
|
13 | import { LightningElement } from 'lwc';
|
14 |
|
15 | export default class WireExample extends {
|
16 | @api bookId;
|
17 |
|
18 | @wire(getBook, { id: '$bookId'})
|
19 | book;
|
20 | }
|
21 | ```
|
22 |
|
23 | Wire adapters are part of LWC's reactivity system. An `@wire` takes the name of a wire adapter and an optional configuration object, which is specific to the wire adapter. You can use a `$` to mark the property of a configuration object as reactive. When a reactive property’s value changes, the wire adapter's `update` method executes with the new value. When the wire adapter provisions new data, the component rerenders if necessary.
|
24 |
|
25 | ```js
|
26 | // wire-adapter.js
|
27 | import { bookEndpoint } from './server';
|
28 |
|
29 | export class getBook {
|
30 | connected = false;
|
31 | bookId;
|
32 |
|
33 | constructor(dataCallback) {
|
34 | this.dataCallback = dataCallback;
|
35 | }
|
36 |
|
37 | connect() {
|
38 | this.connected = true;
|
39 | this.provideBookWithId(this.bookId);
|
40 | }
|
41 |
|
42 | disconnect() {
|
43 | this.connected = false;
|
44 | }
|
45 |
|
46 | update(config) {
|
47 | if (this.bookId !== config.id) {
|
48 | this.bookId = config.id;
|
49 | this.provideBookWithId(this.bookId);
|
50 | }
|
51 | }
|
52 |
|
53 | providBookWithId(id) {
|
54 | if (this.connected && this.bookId !== undefined) {
|
55 | const book = bookEndpoint.getById(id);
|
56 |
|
57 | if (book) {
|
58 | this.dataCallback(Object.assign({}, book));
|
59 | } else {
|
60 | this.dataCallback(null);
|
61 | }
|
62 | }
|
63 | }
|
64 | }
|
65 | ```
|
66 |
|
67 | ## Syntax
|
68 |
|
69 | For complete information about syntax, see [lwc.dev/guide/wire_adapter](https://lwc.dev/guide/wire_adapter#wire-adapters).
|
70 |
|
71 | ## Implementation Example
|
72 |
|
73 | The RCast App is a PWA podcast player written with Lightning Web Components.
|
74 |
|
75 | https://github.com/pmdartus/rcast
|