Yuzu can power UIs of any size: from huge sprawling webapps to drop-in UI components. In this example we'll focus on powering something on the small scale: a portable web component that renders a badge with live-updating stock prices, like this:
If you'd rather skip to the good part, we've created a GitHub Repo with our demo code.
Since we want this component to be fully portable and framework-agnostic, we'll be using Lit + Typescript to create a native Web Component. This guide assumes you have the following tools installed:
To get started, we'll use yarn to create a project for us.
$ $ $
The code above creates a new project folder using Vite as the build tool, then moves into the directory and installs dependencies.
Once we're in our new project and have run a fresh
yarn install, let's do a few things.
src/my-element.ts. Let's rename it to
src/yuzu-price-badge.ts, let's replace all occurences of
vite.config.ts, go ahead and do the same thing, replacing all usages of
If that sounds like a lot of work, you can just run these commands in your terminal instead:
$ $ $
Next, let's clean out all the boilerplate from
src/yuzu-stock-price-badge.ts. The file should look about this this when you're done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Ok, now that we're at a good baseline, let's add some properties to our new component, just above our render method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Our two new properties,
symbol will be exposed in HTML to change what's rendered in this badge. The third property,
lastPrice is a bit of internal state that will hold the last known price of our stock. Let's go to index.html and update our component.
1 2 3 4
Great! Now, we need to fetch the last price of our stock when the component loads. We can override the
connectedCallback function from LitElement to do that. Let's put our connectedCallback between our new properties and the render method.
1 2 3
Next, we're going to do two things:
Because Yuzu's streaming APIs only returns data on stocks during market hours, it's good practice to use the GraphQL API to fetch any data you need to render your UI, and then subscribe to subsequent updates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
Great! Here's a quick breakdown of what's happening above:
And we're done!