Last active
February 22, 2020 23:41
-
-
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
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, { 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