Skip to content

Instantly share code, notes, and snippets.

@darde
Last active February 22, 2020 23:41
Show Gist options
  • Save darde/86618db01599272eb9aa5d7e68672f87 to your computer and use it in GitHub Desktop.
Save darde/86618db01599272eb9aa5d7e68672f87 to your computer and use it in GitHub Desktop.
Medium store - Testing asynchronous code with Jest and Testing Library React - src/App.js - part 1
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import fetchPosts from './services/fetchPosts';
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
let mounted = true;
const fetchData = async () => {
const newPosts = await fetchPosts();
if (mounted) {
setPosts(newPosts);
}
}
fetchData();
return () => { mounted = false; };
}, []);
if (posts.length === 0) {
return <span>Loading...</span>;
}
return (
<div className="App">
<ul>
{
posts.map(post => (
<li key={post.id}>{post.title}</li>
))
}
</ul>
</div>
);
}
App.propTypes = {
term: PropTypes.string,
};
App.defaultProps = {
term: 'posts',
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment