Did you ever feel that most JavaScript frameworks tend to overcomplicate stuff that could be otherwise trivial?
Say we want to render some "loading..." text while another process is pending, then display the results.
Some people call this "Suspense".
We just found a simple and innovative way to do that.
The problem appeared to be challenging because a Promise can only resolve once, but we need both an initial placeholder and a final value.
So, what we can do is just put the initial placeholder in our component as normal, then serve our promise via an Attribute Mixin, a plain object whose attributes get all merged into the given element: if it has a property caleld innerHTML
or innerText
, those will be handled accordingly and used by Rimmel.js to set the corresponding attributes in the DOM.
So, hold tight, here's the code:
import { rml } from 'rimmel';
const getData = () => fetch('/api')
.then(r=>r.text())
.then(t=>({innerHTML: t}))
;
document.body.innerHTML = rml`
<div ...${getData()}>loading...</div>
`;
Try it yourself, play with it on Stackblitz or run it below:
Why this is convenient
It may be intuitive, but the Promise is the standard primitive to handle deferred objects. Created by standard web APIs such as fetch
, it's simple to use and ubiquitous.
More about Attribute Mixins
An Attribute Mixin is a plain object or anything resolving to an object (a function, a promise, an observable) whose properties will be merged into the given element. These include classes, styles, attributes, inner text and HTML, even child nodes, opening a large number of possibilities.
Now, if you like what you've seen here please consider leaving a Github ⭐ Star to motivate our lazy team to keep evolving these patterns for you!
Top comments (0)