Skip to content

Commit

Permalink
Update README.md (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
koddsson authored Apr 23, 2024
1 parent c267e53 commit 348b133
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,51 @@

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

## Installation

```sh
npm install --save @koddsson/context-protocol
```

## Usage

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.

```ts
import { ProviderMixin } from "@koddsson/context-protocol";

export class ProviderElement extends ProviderMixin(HTMLElement) {
// Set any data contexts here.
contexts = {
"number-of-unread-messages": () => {
return 0;
},
};

async connectedCallback() {
// It's also possible to provide context at any point using `updateContext`.

const response = await fetch('/api/messages/');
const data = await response.json();
this.updateContext('number-of-unread-messages', data.unreadCount);
}
}
```

```ts
import { ConsumerMixin } from "@koddsson/context-protocol";

export class ConsumerElement extends ConsumerMixin(HTMLElement) {
contexts = {
// Fetch contexts that we care about and subscribe to any changes.
"number-of-unread-messages": (count: number) => {
this.textContent = `${count} unread messages!`;
},
};

connectedCallback() {
// It's also possible to get any context on demand without subscribing.
this.textContent = this.getContext('number-of-unread-messages');
}
}
```

0 comments on commit 348b133

Please sign in to comment.