Skip to content

Instantly share code, notes, and snippets.

@mahdiyazdani
Created November 27, 2020 14:31
Show Gist options
  • Save mahdiyazdani/5589f983fe71e6bee72189551973b1dc to your computer and use it in GitHub Desktop.
Save mahdiyazdani/5589f983fe71e6bee72189551973b1dc to your computer and use it in GitHub Desktop.
Fetch and display data with `useEffect`
// 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