choojs / choojs/choo

New feature: Async route support

Open
#708 1 comment 4 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
6.8k
Forks
573
PR merge metrics
No merged PRs in 30d

Description

Hi,
Really liking Choo so far! One thing I was missing was the ability to define an async route (I'm working on a game and wanted to preload assets). I didn't see a simple way to accomplish this (maybe I missed something obvious), so I wrote a little module that augments app with an `asyncRoute` method:

```javascript
const app = withAsyncRoute(choo());

app.asyncRoute('/', loadResources,
() => html`

Loading...

`,
(state, emit, data) => html`
Loaded ${data}
`
(state, emit, err, params) => {
console.error('error loading /:', params, err, state);
return html`

Error loading / (see console)



`;
},
);
```

Was wondering if there's interest in either merging this function into Choo proper, or as a third-party npm module?

For reference, here's the module -- it's pretty simple:

```javascript
module.exports = (app) => Object.assign(app, {
/**
* @param {string} route
* @param {Promise|Function>} promise
* @param {Function} loadingHandler
* @param {Function} loadedHandler
* @param {Function} errorHandler
*/
asyncRoute: (route, promise, loadingHandler, loadedHandler, errorHandler) => {
app.use((state, emitter) => {
const emit = emitter.emit.bind(emitter);

app.router.on(route, (params) => {
state.params = params;

if (typeof promise === 'function') {
promise = promise();
}

let completed = false;
let isError = false;
let data = null;

promise.then(result => {
completed = true;
data = result;
emitter.emit('render');
}).catch(err => {
completed = isError = true;
data = err;
emitter.emit('render');
});

return () => {
if (!completed) {
return loadingHandler(state, emit, params);
} else if (isError) {
return errorHandler(state, emit, data, params);
} else {
return loadedHandler(state, emit, data, params);
}
};
});
});
}
});
```

Contributor guide

Open the contributing guide

Research direction

Review the existing app.use and app.router.on APIs before assessing how asyncRoute would fit Choo. Compare the proposed loading, loaded, and error handlers with current route behavior and determine whether the feature belongs in Choo or as a third-party module; done requires an agreed scope and implementation direction.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend, web-dev
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.