Skip to content

Default value for Async Provider? #315

Answered by keithamus
andy-UKC asked this question in Q&A
Discussion options

You must be logged in to vote

Async is determined by the provider; the consumer has no knowledge of how the provider gets its data. In these cases it's probably best to give the consumer a default.

@controller
@providable
class ServerState extends HTMLElement {
  @provideAsync get hitCount(): Promise<number> {
    return (async () => {
      const res = await fetch('/hitcount')
      const json = await res.json()
      return json.hits
    })()
  }
}

@controller
class HitCount extends HTMLElement {
  @consume hitCount = 0;
}

If you want your consumer to have side-effects when it is set - as well as having a default - it's not quite so straightforward. One way to do this would be to encapsulate the value as a private …

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@andy-UKC
Comment options

@keithamus
Comment options

@andy-UKC
Comment options

@keithamus
Comment options

@andy-UKC
Comment options

Answer selected by keithamus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants