Skip to content

Instantly share code, notes, and snippets.

@ahayes91
Last active June 12, 2021 20:17
Show Gist options
  • Save ahayes91/09cf698ecf497fcea45630983492d763 to your computer and use it in GitHub Desktop.
Save ahayes91/09cf698ecf497fcea45630983492d763 to your computer and use it in GitHub Desktop.
create-react-app App.js file with some simple and quick modifications to display a button that makes an API request, and shows the result in a table, or an error message based on the response of that request.
import { useState, useCallback } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [posts, setPosts] = useState([]);
const [error, setError] = useState(false);
const fetchRequest = useCallback(() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(({ data }) => {
setPosts(data);
})
.catch(() => setError(true));
}, []);
if (error) {
return (
<>
<header className="App-header">
<p>Whoops! Something went wrong. Try refreshing the page!</p>
</header>
</>
)
}
return (
<div>
<header className="App-header">
<button onClick={fetchRequest}>Click me to fetch posts!</button>
{posts.length > 0 && (
<table>
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
{posts.map(post => (
<tr key={post.id}>
<td>{post.title}</td>
</tr>
))}
</tbody>
</table>
)}
</header>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment