Created
August 14, 2019 21:28
-
-
Save nem035/267f8fa4524cb660d3669ec0a9b951a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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