Skip to content

Instantly share code, notes, and snippets.

@ianmstew
Last active November 25, 2019 03:44
Show Gist options
  • Save ianmstew/f8eadd183206e34e991a590cba39dfc0 to your computer and use it in GitHub Desktop.
Save ianmstew/f8eadd183206e34e991a590cba39dfc0 to your computer and use it in GitHub Desktop.
asyncComputed example
// Parallel implementation to Avatar example from
// https://github.com/conorhastings/use-reducer-with-side-effects/blob/19d097e95302068d8368b0a10b379b0a6bab9f93/README.md
import { useObserver, useLocalStore } from 'mobx-react';
// WIP library inspired by `import { promisedComputed } from 'async-computed-mobx'`
import asyncComputed from 'utils/mobx/asyncComputed';
const DEFAULT_AVATAR = '/assets/img/default-avatar.png';
function Avatar(props: { userName: string }) {
const store = useLocalStore((observableProps) => new class Store {
avatarAsync = asyncComputed(
{
defaultValue: DEFAULT_AVATAR
},
() => fetch(`/avatar/${observableProps.userName}`)
)
}, props);
return useObserver(() => (
<div>
<img src={store.avatarAsync.get()} />
<div>
Busy: {store.avatarAsync.busy ? 'true' : 'false'}
</div>
<div>
Has error: {store.avatarAsync.error ? 'true' : 'false'}
</div>
<div>
Has ever resolved: {store.avatarAsync.resolved ? 'true' : 'false'}
</div>
</div>
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment