Skip to content

Instantly share code, notes, and snippets.

@Jacobkyalo
Created July 29, 2022 05:24
Show Gist options
  • Save Jacobkyalo/92fee7e50f2504e116e6e7d272146dae to your computer and use it in GitHub Desktop.
Save Jacobkyalo/92fee7e50f2504e116e6e7d272146dae to your computer and use it in GitHub Desktop.
jsonplaceholder api
import React from "react";
import PostDetails from "./components/PostDetails";
import Posts from "./components/Posts";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
const App = () => {
return (
<div className="app">
<Router>
<Routes>
<Route path="/" element={<Posts />} />
<Route path="/post/:id" element={<PostDetails />} />
</Routes>
</Router>
</div>
);
};
export default App;
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "../App.css";
const Posts = () => {
const [posts, setPosts] = useState([]);
const fetchPosts = async () => {
const data = await fetch("https://jsonplaceholder.typicode.com/posts");
const json = await data.json();
setPosts(json);
};
const truncate = (str, n) => {
return str?.length > n ? str.substr(0, n - 1) + "..." : str;
};
useEffect(() => {
fetchPosts();
}, []);
return (
<div className="posts">
{posts &&
posts.map((post) => (
<div key={post.id} className="post">
<h2>{truncate(post.title, 20)}</h2>
<p>{truncate(post.body, 40)}</p>
<Link to={`/post/${post.id}`}>
<p>view more...</p>
</Link>
</div>
))}
</div>
);
};
export default Posts;
import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
const Post = () => {
const [post, setPost] = useState([]);
const params = useParams();
const navigate = useNavigate();
const fetchPost = async () => {
const data = await fetch(
`https://jsonplaceholder.typicode.com/posts/${params.id}`
);
const json = await data.json();
setPost(json);
};
useEffect(() => {
fetchPost();
}, []);
return (
<div>
{post && (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
<button onClick={() => navigate("/")} type="button">
Go Home
</button>
</div>
)}
</div>
);
};
export default Post;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment