import { useState, useEffect, useCallback, FormEvent } from "react"; type article = { id: number; title: string; photoUrl: string; content: string; createdBy: string; createdOn: string; updateOn: string; }; // if null then code will know to not search and just return all articles type articleSearch = { set: React.Dispatch>; value: string | null; }; export default function Home({ articleSearch, username, }: { articleSearch: articleSearch; username: string | null; }) { const [articles, setArticles] = useState([]); const [allArticles, setAllArticles] = useState([]); const handleDelete = async (e: FormEvent) => { e.preventDefault(); const target = e.target as typeof e.target & { id: { value: string }; }; const response = await fetch( `${import.meta.env.VITE_API_TITLE}/api/v1/articles/delete/${target.id.value}`, { credentials: "include", method: "get", }, ); if (!response.ok) { console.log(response); alert("check console for error"); } else { fetchArticles(); } }; function renderButtons(article: article) { return (
Edit
); } const fetchArticles = useCallback(() => { let url; if (articleSearch.value === null) { //alert("not searched"); url = `${import.meta.env.VITE_API_TITLE}/api/v1/articles`; } else { //alert("searched"); url = `${import.meta.env.VITE_API_TITLE}/api/v1/articles?search=${ articleSearch.value }`; } fetch(url) .then((response) => { if (response.ok) { return response.json(); } throw new Error("Network response was not ok."); }) .then((response) => setArticles(response)); }, [articleSearch.value]); // pull data when new search is given useEffect(() => { fetchArticles(); }, [articleSearch.value, fetchArticles]); // when new data is pulled update the articles shown useEffect(() => { setAllArticles( articles.map((article) => (
{/*th:href="@{/articles/{articleId}(articleId=${article.id})}"*/}
{article.title}

{username == article?.createdBy && renderButtons(article)}

)), ); }, [articles, username]); return ( <> {/*Container*/}
); }