Skip to content

Instantly share code, notes, and snippets.

@nem035
Created August 14, 2019 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nem035/267f8fa4524cb660d3669ec0a9b951a5 to your computer and use it in GitHub Desktop.
Save nem035/267f8fa4524cb660d3669ec0a9b951a5 to your computer and use it in GitHub Desktop.
import React from "react";
import ReactDOM from "react-dom";
class Async extends React.Component {
state = { isLoading: false };
componentDidCatch(x) {
if (x instanceof Promise) {
this.setState({ isLoading: true });
x.then(() => {
this.setState({ isLoading: false });
});
} else {
throw x;
}
}
render() {
return this.state.issLoading ? this.props.fallback : this.props.children;
}
}
let cache = new Map();
let pending = new Map();
function fetchSync(url) {
if (cache.has(url)) {
return cache.get(url);
}
if (pending.has(url)) {
throw pending.get(url);
}
let promise = fetch(url)
.then(response => response.text())
.then(text => {
pending.delete(url);
cache.set(url, text);
});
pending.set(url, promise);
throw promise;
}
function getUserName() {
return JSON.parse(
fetchSync(`http://faker.hook.io?property=internet.userName`)
);
}
function Greeting(name) {
return fetchSync(`http://faker.hook.io?property=company.bsBuzz`);
}
function Message() {
let name = getUserName();
return (
<span>
<Greeting name={name} />, {name}!
</span>
);
}
function App() {
return (
<Async>
<Message fallback={"Loading..."} />
</Async>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment