Skip to content

Instantly share code, notes, and snippets.

@jayallen
Created May 22, 2018 18:28
Show Gist options
  • Save jayallen/746f122d70301502dcd0ad5bb46015cc to your computer and use it in GitHub Desktop.
Save jayallen/746f122d70301502dcd0ad5bb46015cc to your computer and use it in GitHub Desktop.
Test of concurrent fetches in React componentDidMount
// In response to https://stackoverflow.com/questions/50456959/call-async-await-functions-in-parallel-not-working-on-reacts-componentdidmount/50458425#50458425
// The following code, bootstrapped with create-react-app, definitely fetches the resources concurrently
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor() {
super()
this.state = {
loading: true,
result: []
}
}
async fetcher(url) {
try {
const response = await fetch(url)
let json = null
if (response.ok) {
json = await response.json()
} else if (response.status !== 200) {
throw new Error('Error when calling API')
}
console.log(json)
return json
} catch (err) {
console.error(err)
}
}
async componentDidMount() {
const first = this.fetcher('https://api.github.com')
const second = this.fetcher('https://api.github.com')
const result = [ await first, await second ]
console.log(result)
this.setState({ loading: false, result: result })
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
Loading: { this.state.loading ? 'Yes' : 'No' }
</p>
<p>See console for results</p>
</div>
);
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment