Created
November 27, 2020 14:31
-
-
Save mahdiyazdani/5589f983fe71e6bee72189551973b1dc to your computer and use it in GitHub Desktop.
Fetch and display data with `useEffect`
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
// 1. Destructure the `subreddit` from props: | |
function Reddit({ subreddit }) { | |
const [posts, setPosts] = useState([]); | |
useEffect(() => { | |
async function fetchData() { | |
// 2. Use a template string to set the URL: | |
const res = await fetch( | |
`https://www.reddit.com/r/${subreddit}.json` | |
); | |
const json = await res.json(); | |
setPosts(json.data.children.map(c => c.data)); | |
} | |
fetchData(); | |
// 3. Re-run this effect when `subreddit` changes: | |
}, [subreddit, setPosts]); | |
return ( | |
<ul> | |
{posts.map(post => ( | |
<li key={post.id}>{post.title}</li> | |
))} | |
</ul> | |
); | |
} | |
// 4. Pass "reactjs" as a prop: | |
ReactDOM.render( | |
<Reddit subreddit='reactjs' />, | |
document.querySelector("#root") | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment