Skip to content

Instantly share code, notes, and snippets.

@amElnagdy
Created April 15, 2020 21:06
Show Gist options
  • Save amElnagdy/cf80b9437835ea407cc4ec651fc4bd13 to your computer and use it in GitHub Desktop.
Save amElnagdy/cf80b9437835ea407cc4ec651fc4bd13 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
function App() {
const [postList, setPostList] = useState([]);
const [currentPost, setCurrentPost] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [postClicked, setPostClicked] = useState(false);
const fetchPosts = () => {
fetch(`https://www.codeinwp.com/wp-json/wp/v2/posts?per_page=5`)
.then((res) => res.json())
.then((posts) => {
setPostList(posts);
setIsLoading(false);
})
.catch((error) => console.error(error));
};
useEffect(() => {
setIsLoading(true);
fetchPosts();
}, []);
const handleClick = (e) => {
setCurrentPost(postList.find((post) => (post.id = e.target.id)));
setPostClicked(true);
};
return (
<>
{!postClicked ? (
isLoading ? (
<p>LOADING POSTS ...!</p>
) : (
<ul>
{postList.map((post) => (
<li key={post.slug}>
<a id={post.id} href="#" onClick={handleClick}>
{post.title.rendered}
</a>
</li>
))}
</ul>
)
) : (
<>
<button
onClick={() => {
setCurrentPost(null);
setPostClicked(false);
}}
>
Back to Posts
</button>
<h2>{currentPost.title.rendered}</h2>
<p
dangerouslySetInnerHTML={{ __html: currentPost.content.rendered }}
></p>
</>
)}
</>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment