Skip to content

Commit

Permalink
✨ feat(posts, creating post, updating and deleting): fetch and edit p…
Browse files Browse the repository at this point in the history
…osts

fetching posts, editing, deleting and creating new post
  • Loading branch information
AliNough committed Oct 15, 2023
1 parent 5f21f5f commit 6ae89c9
Show file tree
Hide file tree
Showing 10 changed files with 275 additions and 188 deletions.
Binary file added src/assets/defaultprofilepic.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
101 changes: 67 additions & 34 deletions src/components/fetchPosts/index.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { useEffect, useState } from "react";
import { API_URL } from "../../lib/constants";
import PostEditing from "../postEditing";
import { Link } from "@tanstack/react-router";
// import { Link } from "@tanstack/react-router";

export default function FetchPosts() {
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [searchInput, setSearchInput] = useState("");

useEffect(() => {
const GetPosts = async () => {
Expand All @@ -30,7 +33,7 @@ export default function FetchPosts() {
const accessToken = localStorage.getItem("access_token");

const url = new URL(`${API_URL}/social/posts`);
console.log(url);

url.searchParams.append("_author", "true");
url.searchParams.append("_comments", "true");
url.searchParams.append("_reactions", "true");
Expand All @@ -42,40 +45,51 @@ export default function FetchPosts() {
});

const allPosts = await response.json();
setPosts(allPosts);
console.log(allPosts);

// eslint-disable-next-line no-unused-vars
const formattedDate = allPosts.map((post) => {
const originalDateString = post.created;
const date = new Date(originalDateString);

const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0"); // Months are zero-based
const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
// eslint-disable-next-line no-unused-vars
const dateFormated = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
const filteredPosts = allPosts.filter((post) => {
return post.title.toLowerCase().includes(searchInput.toLowerCase());
});

setPosts(filteredPosts);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
};
GetPosts();
const updatePosts = async () => {
try {
}, [searchInput]);

}
}
}, []);
if (isLoading) return <h1>Loading...</h1>;
const handleOnSearch = (srchInp) => {
setSearchInput(srchInp);
};

if (isLoading)
return (
<div className="text-center">
<div role="status">
<svg
aria-hidden="true"
className="inline w-8 h-8 mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
<span className="sr-only">Loading...</span>
</div>
</div>
);
if (error) return <h1>Something went wrong! {error?.message}</h1>;

return (
<>
<div className="bg-blue-50 py-12 sm:py-12">
Expand All @@ -85,7 +99,15 @@ export default function FetchPosts() {
New Posts
</h2>
</div>

<input
type="search"
placeholder="Search"
className="px-2 font-light border-2 bg-blue-100 border-blue-500 rounded-3xl"
id="searchInput"
onKeyUp={(event) => {
handleOnSearch(event.target.value);
}}
/>
<div className="mx-auto mt-1 flex flex-col max-w-2xl gap-x-8 py-3 sm:mt-1 lg:mx-0 lg:max-w-none ">
{posts.map(({ title, id, author, body, created, media }) => (
<article
Expand All @@ -94,11 +116,20 @@ export default function FetchPosts() {
>
<div className="text-sm leading-6">
<div className="relative flex items-center gap-x-3">
<img
src={author.avatar}
alt=""
className="h-10 w-10 rounded-full bg-gray-50"
/>
{author.avatar ? (
<img
src={author.avatar}
alt=""
className="h-10 w-10 rounded-full bg-gray-50"
/>
) : (
<img
src="src/assets/defaultprofilepic.png"
alt=""
className="h-10 w-10 rounded-full bg-gray-50"
/>
)}

<p className="font-semibold cursor-pointer text-gray-900 hover:text-blue-500 ">
<a href={author.href}>
<span className="absolute inset-0" />
Expand All @@ -114,13 +145,15 @@ export default function FetchPosts() {
</div>
</div>
<div className="group border-1 relative px-3 py-1">
<h2 className=" text-lg">{title}</h2>
<p className="mt-1 line-clamp-3 text-sm leading-6 text-gray-600">
{body}
</p>
<img className="rounded-sm" src={media} alt="" />
<Link to={`/post/${id}?id=${id}`}>
<h2 className=" text-lg">{title}</h2>
<p className="mt-1 line-clamp-3 text-sm leading-6 text-gray-600">
{body}
</p>
<img className="rounded-sm" src={media} alt="" />
</Link>
</div>
<button >Edit</button>
<PostEditing id={id} />
</article>
))}
</div>
Expand Down
12 changes: 10 additions & 2 deletions src/components/navbar/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { Link } from "@tanstack/react-router";
export default function Navigation() {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

function handleOnSearch(srchInp) {
console.log(srchInp);
}

return (
<>
<nav className="bg-white border-2 border-white border-b-blue-500">
Expand Down Expand Up @@ -47,9 +51,13 @@ export default function Navigation() {
Login
</Link>
<input
type="text"
type="search"
placeholder="Search"
className="px-2 font-light border-2 border-blue-500 rounded-3xl"
className="px-2 font-light border-2 bg-blue-100 border-blue-500 rounded-3xl"
id="searchInput"
onKeyUp={(event) => {
handleOnSearch(event.target.value);
}}
/>
</div>

Expand Down
122 changes: 122 additions & 0 deletions src/components/postEditing/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { useState } from "react";
import { API_URL } from "../../lib/constants";
import { PostShape } from "../../lib/types";

export default function ManipulatePost({ id = "no id" }) {
const [isEditing, setIsEditing] = useState(false);
const accessToken = localStorage.getItem("access_token");

async function deletePost(postId) {
try {
const response = await fetch(`${API_URL}/social/posts/${postId}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});

const json = await response.json();
console.log("deleted post>", json);
} catch (error) {
console.warn("deletePost error", error);
} finally {
null;
}
}

async function handleOnEdit() {
setIsEditing(true);
}
async function handleOnDelete() {
deletePost(id);
}
async function editPost(event) {
event.preventDefault();
handleOnEdit();

const { body, title, postId } = event.target.elements;

const formattedPostId = Number(postId.value);

const payload = {
title: title.value,
body: body.value,
};

try {
const response = await fetch(
`${API_URL}/social/posts/${formattedPostId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json; charset=UTF-8",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(payload),
}
);

const json = await response.json();

console.warn("Success, updated post!", json);
} catch (error) {
console.warn("Couldn't update post", error);
} finally {
null;
}
}
return (
<>
{isEditing ? (
<>
<form
className="flex gap-2"
onSubmit={(event) => editPost(event, setIsEditing)}
>
<input type="hidden" name="postId" id="postId" value={id} />
<input
className="bg-blue-100 px-1 hover:bg-blue-200 rounded-sm"
name="title"
id="title"
type="text"
placeholder="Title"
/>
<input
className="bg-blue-100 px-1 hover:bg-blue-200 rounded-sm"
name="body"
id="body"
type="text"
placeholder="Body"
/>
<input
className="bg-blue-300 hover:bg-blue-400 px-3 py-1 cursor-pointer rounded-sm "
type="submit"
value="Update"
/>
<button
className="bg-red-100 px-2 hover:bg-red-300 rounded-sm"
onClick={() => setIsEditing(false)}
>
X
</button>
</form>
</>
) : (
<button
className="bg-blue-300 hover:bg-blue-500 rounded-sm px-3 "
onClick={editPost}
>
Edit
</button>
)}
<button
onClick={handleOnDelete}
className="bg-red-200 rounded-sm self-end px-3 hover:bg-red-500"
>
Delete
</button>
</>
);
}
ManipulatePost.propTypes = PostShape;
52 changes: 52 additions & 0 deletions src/components/singlePostPage/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { useEffect, useState } from "react";
import { API_URL } from "../lib/constants";

const initialPostState = {
title: "No post found",
body: "Nothing to see here",
userId: null,
id: null,
};

export default function PostPage() {
const [post, setPost] = useState(initialPostState);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
const fetchData = async () => {
try {
const params = new URLSearchParams(window.location.search);
const postId = params.get("id");
const accessToken = localStorage.getItem("access_token");
const resp = await fetch(`${API_URL}/social/posts/${postId}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const data = await resp.json();
setPost(data);
console.log(data);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
};

fetchData();
}, []);

if (isLoading) return <h1>Loading...</h1>;
if (error) return <h1>Something went wrong! {error?.message}</h1>;

return (
<>
<section>
<h2>{post?.title}</h2>
<p>{post?.body}</p>
<img className="max-w-lg" src={post.media} alt="" />
</section>
</>
);
}
Loading

0 comments on commit 6ae89c9

Please sign in to comment.