fixed issue with reload page, & added food claim page

This commit is contained in:
Leo Wen
2025-04-12 18:09:21 -07:00
parent 569dd066c5
commit 154b490fdf
9 changed files with 142 additions and 93 deletions
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 MiB

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

+46 -37
View File
@@ -32,7 +32,7 @@ function App() {
const [querying, setQuerying] = useState(false);
const [initialized, setIntialized] = useState(false);
const [initialized, setInitialized] = useState(false);
const [filter, setFilter] = useState<Filter>({});
@@ -59,50 +59,60 @@ function App() {
}
}, [college, professor, classParam])
// Handle query changes with debounce
// Perform a search with initialQuery on startup
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedQuery(query);
}, 100);
return () => clearTimeout(timer);
}, [query]);
if (initialQuery) {
setQuery(initialQuery); // Set the query to initialQuery
setDebouncedQuery(initialQuery); // Ensure debouncedQuery is also updated
setInitialized(true); // Mark the component as initialized
handleSearch(initialQuery); // Perform the search with initialQuery
console.log("Performing search with initialQuery:", initialQuery);
} else {
// If no initialQuery, fallback to debouncedQuery
setInitialized(true); // Mark the component as initialized
handleSearch(debouncedQuery); // Perform the search with debouncedQuery
console.log("No initialQuery, performing search with debouncedQuery:", debouncedQuery);
}
}, []); // Run only on component mount
// Trigger search when debouncedQuery changes
useEffect(() => {
if (initialSearchPerformed) {
handleSearch();
if (initialized) {
handleSearch(debouncedQuery); // Perform the search with debouncedQuery
console.log("Performing search with debouncedQuery:", debouncedQuery);
}
}, [debouncedQuery]);
}, [debouncedQuery]); // Run whenever debouncedQuery changes
// Trigger search when filters change
useEffect(() => {
handleSearch();
setInitialSearchPerformed(true);
}, [filter]);
async function handleSearch() {
if (!initialized) return;
if (query === "admin") {
navigate('admin');
if (initialized) {
handleSearch(debouncedQuery); // Perform the search with the current query and filters
console.log("Performing search with updated filters:", filter);
}
}, [filter]); // Run whenever filters change
async function handleSearch(queryToSearch = debouncedQuery) {
setQuerying(true);
let end = ``;
if (filter.school) end += `&s=${filter.school}`;
if (filter.professor) end += `&p=${filter.professor}`;
if (filter.class) end += `&c=${filter.class}`;
try {
var response = await fetch(`${server}/search/?q=${debouncedQuery}${end}`);
var data = await response.json();
console.log("Fetching search results for query:", queryToSearch);
const response = await fetch(`${server}/search/?q=${queryToSearch || ""}${end}`);
const data = await response.json();
setQuerying(false);
setSyllabi(data);
} catch {
console.error("error")
console.log("Search results:", data);
} catch (error) {
console.error("Error fetching search results:", error);
setQuerying(false);
}
}
const location = useLocation();
useEffect(() => {
@@ -123,12 +133,6 @@ function App() {
},
[location])
useEffect(() => {
setQuery(initialQuery);
setIntialized(true);
handleSearch();
console.log("initialQuery set to" + initialQuery)
}, [])
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
@@ -141,17 +145,18 @@ function App() {
<>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
{isMobile() === false &&
<div className="w-full flex place-items-center justify-center pt-1">
<div className="w-full flex place-items-center justify-center pt-16">
<div className="w-3/4 flex justify-center items-center">
<div className="place-items-center justify-center flex w-full flex-col">
<div className="w-full flex space-y-2 flex-col">
<div className="flex pt-2">
<div className="flex flex-col pt-2">
<text className="text-left pl-3">Search for classes by class name or professor name:</text>
<div className="flex-1 flex border border-gray-400 focus:outline-none rounded-lg">
<input
type="search"
onKeyDown={handleKeyDown}
placeholder="search, hit enter or the search button to enter query"
placeholder="search bar..."
className="focus:outline-none placeholder:text-gray-500 font-normal focus:ring-0 bg-transparent border-none rounded-lg flex-1 text-black"
value={query}
onChange={(e) => setQuery(e.target.value)}>
@@ -161,7 +166,7 @@ function App() {
close
</span>
</button>
<button className="aspect-square p-2 flex justify-center items-center" onClick={handleSearch}>
<button className="aspect-square p-2 flex justify-center items-center" onClick={() => handleSearch}>
<span className="material-symbols-rounded hover:text-black text-gray-500">
search
</span>
@@ -283,6 +288,10 @@ function App() {
<span className="text-md">{filter.professor}</span>
<button className="text-md text-red-700" onClick={() => setFilter({ ...filter, professor: undefined })}>Clear</button>
</div>}
<div className="p-2 shadow-2xl rounded-md flex bg-orange-500 flex-col gap-1 border">
<text className=" text-red-100">jfk college success club event:</text>
<img className="p-2 shadow-md bg-white rounded-md border" src="/advertisement.png"/>
</div>
</div>
</div>
@@ -314,7 +323,7 @@ function App() {
<input type="search" onKeyDown={handleKeyDown} placeholder="search class or professor" className="focus:outline-none w-4/5 bg-transparent border-none flex-1 text-black" value={query} onChange={(e) => setQuery(e.target.value)}>
</input>
<button className="aspect-square flex justify-center bg-white rounded-lg items-center" onClick={handleSearch}>
<button className="aspect-square flex justify-center bg-white rounded-lg items-center" onClick={() => handleSearch}>
<span className="material-symbols-rounded text-black">
search
</span>
+2 -1
View File
@@ -16,7 +16,7 @@ function Layout({ children }: { children: React.ReactNode }) {
return (
<div className="bg-[#fcfffd] text-[#051008] w-full h-full">
<div className={`w-full sticky shadow-sm top-0 left-0 backdrop-blur-md z-50 text-left p-2 flex place-items-center justify-center border-b border-gray-300`}>
<div className={`w-full absolute shadow-sm top-0 left-0 backdrop-blur-md z-50 text-left p-2 flex place-items-center justify-center border-b border-gray-300`}>
<div className={`flex-1 gap-4 place-items-center ${!isMobile() ? "flex" : "flex flex-col"}`}>
{isMobile() ?
<button onClick={() => navigate("/upload")} className="p-1 flex-1 rounded-full hover:drop-shadow-xl hover:bg-slate-950 pl-2 pr-2 font-bold bg-black">
@@ -64,6 +64,7 @@ function Layout({ children }: { children: React.ReactNode }) {
</div>
</div>
{children}
</div>
)
}
+2
View File
@@ -11,6 +11,7 @@ import Layout from './Layout.tsx';
import UploadSyllabi from './pages/UploadSyllabi.tsx';
import Professor from './pages/Professor.tsx';
import Welcome from './welcome.tsx';
import UploadSuccessfull from './pages/UploadSuccessFull.tsx';
const server = "https://api.sharesyllabus.me";
export default server;
@@ -28,6 +29,7 @@ createRoot(document.getElementById('root')!).render(
<Route path="/syllabus/:id" element={<Layout><Syllabus /></Layout>} />
<Route path="/upload" element={<Layout><UploadSyllabi /></Layout>} />
<Route path="/professor/:id" element={<Layout><Professor /></Layout>} />
<Route path="/upload_successfull/:id" element={<Layout><UploadSuccessfull /></Layout>} />
</Routes>
</HashRouter>
);
+2 -1
View File
@@ -14,10 +14,11 @@ function Syllabus() {
const [syllabus, getSyllabus] = useState<ClassListing | undefined>(undefined);
useEffect(() => {
console.log(`${server}/syllabus/${id}`)
fetch(`${server}/syllabus/${id}`)
.then(response => response.json())
.then(data => getSyllabus(data))
.then(data => console.log(data))
.then(data => console.log(data + "data"))
}, [id]);
return (
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ClassListing } from "../components/syllabus_comp";
import server from "../main";
function UploadSuccessfull() {
const { id } = useParams();
const [classListing, setClassListing] = useState<ClassListing | null>();
const [dailyFreeFood, setDailyFreeFood] = useState<string | null>("false");
useEffect(() => {
fetch(`${server}/syllabus/${id}`)
.then(response => response.json())
.then(data => setClassListing(data))
.then(data => console.log(data))
const savedValue = localStorage.getItem('dailyFreeFood');
setDailyFreeFood(savedValue);
if (!savedValue) {
localStorage.setItem('dailyFreeFood', "false");
}
}, [id])
return (
<div className={`flex flex-col items-center justify-center h-screen ${dailyFreeFood ? "bg-gray-100" : "bg-green-400"}`}>
<text className="font-black text-yellow-400 text-5xl mb-10">{(dailyFreeFood == "false") ? "community service hours will be sent digitally" : "CLAIM FREE FOOD"}</text>
<h1 className="text-2xl font-bold mb-4">Upload Successful</h1>
<p className="text-lg">Your file has been uploaded successfully!</p>
<p>{JSON.stringify(classListing)}</p>
</div>
);
}
export default UploadSuccessfull;
+43 -42
View File
@@ -1,5 +1,7 @@
import React, { useEffect, useState } from "react";
import server from "../main";
import AsyncSelect from "react-select/async";
import { useNavigate } from "react-router-dom";
export interface Class {
id: number;
@@ -26,24 +28,23 @@ function UploadSyllabi() {
const [classLength, setClassLength] = useState(0);
const [textbookCost, setTextbookCost] = useState("free");
const [classDescription, setClassDescription] = useState("");
const [classAbrvOptions, setClassAbrvOptions] = useState<Class[] | null>(null);
const [classAbrvQuery, setClassAbrvQuery] = useState("");
const navigate = useNavigate();
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [collegeOptions, setCollegeOptions] = useState<School[]>([]);
const [professorOptions, setProfessorOptions] = useState<Professor[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetch(`https://api.sharesyllabus.me/schools`, {
method: "GET",
}).then((res) => res.json()).then((data) => {
setCollegeOptions(data);
});
setCollege("RCCD");
}, []);
function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) {
@@ -62,15 +63,7 @@ function UploadSyllabi() {
});
}
function searchClassAbrv(e: React.ChangeEvent<HTMLInputElement>) {
setClassAbrvQuery(e.target.value);
fetch(`${server}/search/class/?q=${classAbrvQuery}&s=${college}`, {
method: "POST",
}).then((res) => res.json()).then((data) => {
setClassAbrvOptions(data);
});
}
function submit(e: React.MouseEvent<HTMLButtonElement>) {
e.preventDefault();
@@ -89,6 +82,7 @@ function UploadSyllabi() {
return;
}
const formData = new FormData();
formData.append("upload", file);
formData.append("className", classAbrvQuery);
@@ -108,7 +102,8 @@ function UploadSyllabi() {
})
.then(async (res) => {
if (res.ok) {
alert("Syllabus uploaded successfully");
const responseBody = await res.json();
navigate(`/upload_successfull/${responseBody.id}`);
} else {
const data = await res.json();
setError(data.msg);
@@ -129,34 +124,39 @@ function UploadSyllabi() {
}, []);
return (
<div className="w-full flex place-items-center justify-center p-10">
<div className="w-full flex place-items-center justify-center p-10 pt-20">
<div className="w-1/2 text-left flex flex-col">
<text className="text-3xl font-bold">Upload a Syllabus!</text>
<text className="italic">If you complete all the information you can receive 2 hrs in community service. Just send us your email so we can give you an E-signature of your hours. If you dont want to do the community service hours, feel free to leave some fields blank.</text>
<div className="flex flex-col pt-2 gap-2">
<text>Syllabus (pdf, docx, etc.)</text>
<input type="file" className="w-min rounded-md bg-white text-black" onChange={handleFileChange}></input>
<text>College District (not school!):</text>
<input
list="collegeOptions"
value={college}
onChange={(e) => setCollege(e.target.value)}
placeholder="Search or select college district"
required
className="p-1 rounded-md bg-white text-black border"
/>
<datalist id="collegeOptions">
{collegeOptions.map((college: School, index: number) => (
<option key={index} value={college.name} />
))}
</datalist>
<text>Class Name:</text>
<input list="classAbrvOptions" className="p-1 rounded-md border bg-white text-black" placeholder="i.e.: ENG-1A" value={classAbrvQuery} disabled={!college} onChange={(e) => searchClassAbrv(e)} required onInput={(e) => setClassAbrvQuery(e.currentTarget.value)} />
<datalist id="classAbrvOptions" className="w-full bg-white">
{classAbrvOptions?.map((classOption, index) => (
<option key={index} value={classOption.className} />
))}
</datalist>
<AsyncSelect
className=" bg-white text-black"
placeholder="i.e.: ENG-1A"
value={classAbrvQuery ? { label: classAbrvQuery, value: classAbrvQuery } : null}
loadOptions={async (inputValue) => {
if (!inputValue || !college) return [];
const response = await fetch(`${server}/search/class/?q=${inputValue}&s=${college}`, {
method: "POST",
});
const data = await response.json();
return data.map((classOption: Class) => ({
label: classOption.className,
value: classOption.className,
}));
}}
onChange={(selectedOption) => {
if (selectedOption) {
setClassAbrvQuery(selectedOption.value);
}
}}
isSearchable={true}
cacheOptions
defaultOptions
/>
<text>Professor:</text>
<input placeholder="enter or search professor" className="p-1 rounded-md bg-white border text-black" list="professorOptions" value={professor} disabled={!college} required onChange={searchProfessor}></input>
<datalist id="professorOptions">
@@ -164,10 +164,10 @@ function UploadSyllabi() {
<option key={index} value={professor.name} />
))}
</datalist>
<text>Duration of class in weeks: [OPTIONAL: community service hours]</text>
<text>Duration of class in weeks. [OPTIONAL: community service hours] <span className="text-orange-700 font-light">For Fall/Spring classes put 16, for winter/summer put 6:</span></text>
<input type="number" className="p-1 rounded-md bg-white text-black" value={classLength} onChange={(e) => setClassLength(Number(e.target.value))}></input>
<text>Textbook Cost: [OPTIONAL: community service hours]</text>
<select className="p-1 rounded-md bg-white text-black" value={textbookCost} onChange={(e) => {setTextbookCost(e.target.value); console.log(e.target.value)}}>
<text>Textbook Cost (access codes too). [OPTIONAL: community service hours] <span className="text-orange-700 font-light">Free $0 | Cheap $1-10 | Moderate $10-40 | Expensive $40 </span></text>
<select className="p-1 rounded-md bg-white text-black" value={textbookCost} onChange={(e) => { setTextbookCost(e.target.value); console.log(e.target.value) }}>
<option>free</option>
<option>cheap</option>
<option>moderate</option>
@@ -179,9 +179,10 @@ function UploadSyllabi() {
<input placeholder="John Doe" className="p-1 rounded-md bg-white border text-black" value={name} onChange={(e) => setName(e.target.value)}></input>
<text>Your Email [OPTIONAL: community service hours]</text>
<input placeholder="example@company.com" className="p-1 rounded-md border bg-white text-black" value={email} onChange={(e) => setEmail(e.target.value)}></input>
<div className="text-right">
<div className="text-right flex place-items-center gap-2 flex-row">
<text className="text-xs pl-40 font-light">if you are at the college success club event, clicking for the first time gives free food & 2 cc hours. if you submit more syllabuses, it will only reward more hours, not food</text>
<button
className="bg-blue-600 rounded-lg p-2 disabled:opacity-50"
className="bg-blue-600 rounded-lg text-white font-bold p-2 disabled:opacity-50"
onClick={submit}
disabled={isLoading}
>