Skip to content

Commit 348b133

Browse files
authored
Update README.md (#15)
1 parent c267e53 commit 348b133

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

README.md

+48
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,51 @@
22

33
A Lit compatible implementation of the [context-protocol community protocol](https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md).
44

5+
## Installation
6+
7+
```sh
8+
npm install --save @koddsson/context-protocol
9+
```
10+
11+
## Usage
12+
13+
A component that implements the ProviderMixin will become a _Provider_ of data and a component that implements the ConsumerMixin will become a _Consumer_ of data.
14+
15+
```ts
16+
import { ProviderMixin } from "@koddsson/context-protocol";
17+
18+
export class ProviderElement extends ProviderMixin(HTMLElement) {
19+
// Set any data contexts here.
20+
contexts = {
21+
"number-of-unread-messages": () => {
22+
return 0;
23+
},
24+
};
25+
26+
async connectedCallback() {
27+
// It's also possible to provide context at any point using `updateContext`.
28+
29+
const response = await fetch('/api/messages/');
30+
const data = await response.json();
31+
this.updateContext('number-of-unread-messages', data.unreadCount);
32+
}
33+
}
34+
```
35+
36+
```ts
37+
import { ConsumerMixin } from "@koddsson/context-protocol";
38+
39+
export class ConsumerElement extends ConsumerMixin(HTMLElement) {
40+
contexts = {
41+
// Fetch contexts that we care about and subscribe to any changes.
42+
"number-of-unread-messages": (count: number) => {
43+
this.textContent = `${count} unread messages!`;
44+
},
45+
};
46+
47+
connectedCallback() {
48+
// It's also possible to get any context on demand without subscribing.
49+
this.textContent = this.getContext('number-of-unread-messages');
50+
}
51+
}
52+
```

0 commit comments

Comments
 (0)