Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

request onScrool #94

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions necchange/src/app/api/feed/feed_post/[...scroll]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export async function GET(req, context) {
lesson_ids = query_lesson_ids.map((lesson_id) => lesson_id.id);
}

console.log("status", status);
const trades = await prisma.trade.findMany({
where: {
status: status,
Expand All @@ -72,10 +71,7 @@ export async function GET(req, context) {
cursor: cursor,
take: limit,
skip: skip,
orderBy: {
id: "asc",
},


include: {
from_student: {
select: {
Expand Down
161 changes: 86 additions & 75 deletions necchange/src/app/feed/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,20 @@ import axios from "axios";
import FeedPost from "@/components/Feed/Feed-Posts/FeedPost";
import Loader from "@/components/globals/Loader";

import { FaPlus } from "react-icons/fa6";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import UCFilter from "@/components/Feed/Sidebar/Filters/UCFilter";
import NewTradeButton from "@/components/Feed/Sidebar/NewTradeButton";
import TimeFilter from "@/components/Feed/Sidebar/Filters/TimeFilter";

const Posts = ({ filteredPosts, toggleLoader, getMorePosts }) => {
const Posts = ({ filteredPosts, toggleLoader }) => {
return (
<div>
<div className="w-full grid gap-6 mb-8">
{filteredPosts.map((feedPost, i) => {
<div className="w-full grid lg:grid-cols-2 gap-10">
{filteredPosts.map((feedPost, i) => {
// console.log("feedPost", feedPost);
return (
<FeedPost key={i} post={feedPost} toggleLoader={toggleLoader} />
);
})}
</div>

<div className="flex justify-center">
<button
className="flex items-center gap-2 rounded-full bg-blue-500 py-2 px-4 text-base capitalize font-semibold text-white"
onClick={getMorePosts}
>
<FaPlus /> carregar mais
</button>
</div>
return <FeedPost key={i} post={feedPost} toggleLoader={toggleLoader} />;
})}
</div>
);
};
Expand Down Expand Up @@ -60,6 +47,8 @@ export default function Feed() {
const [filteredPosts, setFilteredPosts] = useState([]);
const [myTrades, setMyTrades] = useState(false);

const [timeFilter, setTimeFilter] = useState(false);

const toggleLoader = (value) => {
setLoader(value);
};
Expand All @@ -78,75 +67,79 @@ export default function Feed() {
checkTradePeriod();
}, []);


// This effect is responsible to get the first posts that show on feed
useEffect(() => {
const startingFeed = async () => {
try {
toggleLoader(true)
toggleLoader(true);
axios
.get(
`/api/feed/feed_post/${5}/landing/${
`/api/feed/feed_post/${6}/landing/${
myTrades ? `/ ${session?.user?.number}` : "/undefined"
}`
)
.then((res) => {
setDbCursor(res.data.cursor);
setFeedData(res.data.response);
toggleLoader(false)
toggleLoader(false);
});
} catch (error) {
console.error("Error fetching data:", error);
toggleLoader(false)
toggleLoader(false);
}
};

if (tradesOpen) startingFeed();
}, [session, tradesOpen]);


// This effect filters the posts already taken
useEffect(() => {
let posts = []
let posts = [];
// No filters, choose between personal or everything
if (ucsFilter.length == 0) {
posts = feedPosts.filter((feedPost) =>
myTrades
? feedPost.from_student.number == session.user.number
: true
);

if (ucsFilter.length == 0) {
posts = feedPosts
.filter((feedPost) =>
myTrades ? feedPost.from_student.number === session.user.number : true
)
.sort((a, b) =>
timeFilter
? new Date(a.publish_time) - new Date(b.publish_time)
: new Date(b.publish_time) - new Date(a.publish_time)
);
}

// With filters (this body can be optimized)
} else {
posts = feedPosts.filter((feedPost) =>
ucsFilter.every((uc) =>
feedPost.trade_id
.map((trade) => trade.lessonFrom.course.name)
.includes(uc)
) && (myTrades
? feedPost.from_student.number == session.user.number
: feedPost.from_student.number != session.user.number )
else {
posts = feedPosts.filter(
(feedPost) =>
ucsFilter.every((uc) =>
feedPost.trade_id
.map((trade) => trade.lessonFrom.course.name)
.includes(uc)
) &&
(myTrades
? feedPost.from_student.number == session.user.number
: feedPost.from_student.number != session.user.number)
);
}

let new_cursor = 0
const post_ids = posts.map(post => post.id)
new_cursor = post_ids.length == 0 ? 1 : Math.max(...post_ids)
setDbCursor(new_cursor)
let new_cursor = 0;
const post_ids = posts.map((post) => post.id);
new_cursor = post_ids.length == 0 ? 1 : Math.max(...post_ids);
setDbCursor(new_cursor);
setFilteredPosts(posts);

}, [myTrades, ucsFilter, feedPosts]);
}, [myTrades, ucsFilter, feedPosts, timeFilter]);

// This function gets more posts from the database
const getMorePosts = async () => {
toggleLoader(true)
toggleLoader(true);
try {
let query_filtered_ucs = ucsFilter.join("&");
query_filtered_ucs = encodeURIComponent(query_filtered_ucs);
//console.log(dbCursor);
axios
.get(
`/api/feed/feed_post/${5}/${dbCursor}${
`/api/feed/feed_post/${6}/${dbCursor}${
myTrades ? `/${session?.user?.number}` : "/undefined"
}/${query_filtered_ucs}`
)
Expand All @@ -155,20 +148,40 @@ export default function Feed() {
setDbCursor(res.data.cursor);
setFeedData([...feedPosts, ...res.data.response]);
} else {
toast.warning('Não há mais posts, de momento.');
toast.warning("Não há mais posts, de momento.");
}
toggleLoader(false)
toggleLoader(false);
});
} catch (error) {
toggleLoader(false)
toggleLoader(false);
console.error("Error fetching data:", error);
}
};
console.log(feedPosts, "feedPosts");

useEffect(() => {
const handleScroll = (e) => {
const scrollHeight = e.target.documentElement.scrollHeight;
const currentHeight =
e.target.documentElement.scrollTop + window.innerHeight;

if (currentHeight + 1 >= scrollHeight) {
getMorePosts();
}
};

window.addEventListener("scroll", handleScroll);

return () => window.removeEventListener("scroll", handleScroll);
}, [getMorePosts]);

console.log(timeFilter, "timeFilter");

return (
<div className="min-h-screen pt-40 pb-20 flex justify-center bg-white text-gray-900">
<div className="flex flex-col items-center mx-5 w-full max-w-4xl">
<div className="w-full flex flex-col sm:flex-row justify-between items-center gap-2 text-base font-semibold text-gray-900 mb-8">
<div className="min-h-screen pt-40 pb-20 flex flex-col gap-4 items-center bg-white text-gray-900">
<div className="flex flex-col items-center mx-5 w-[90%] max-w-6xl gap-8">
<p className="text-2xl font-bold text-start w-full ">TROCAS DE TURNO</p>
<div className="w-full flex flex-col gap-8 text-base font-semibold text-gray-900 mb-8">
<div className="border-b w-full sm:w-auto grid grid-cols-2">
<button
className={`w-full sm:w-auto py-2 px-3 text-center transition duration-200 border-b-2 ${
Expand All @@ -192,29 +205,27 @@ export default function Feed() {
</button>
</div>

<div className="w-full sm:w-auto flex flex-col sm:flex-row gap-2">
<UCFilter
session={session}
setUcsFilter={setUcsFilter}
setUcsArray={setUcsArray}
ucsArray={ucsArray}
ucsFilter={ucsFilter}
/>
{tradesOpen ? (
<div className="flex-grow">
<div className="w-full sm:w-auto flex flex-col justify-between items-center sm:flex-row gap-2">
<TimeFilter setTimeFilter={setTimeFilter} />
<div className="flex sm:flex-row flex-col gap-4 w-full sm:w-auto">
<UCFilter
session={session}
setUcsFilter={setUcsFilter}
setUcsArray={setUcsArray}
ucsArray={ucsArray}
ucsFilter={ucsFilter}
/>
{tradesOpen ? (
<NewTradeButton toggleLoader={toggleLoader} />
</div>
) : (
<></>
)}
) : (
<></>
)}
</div>
</div>
</div>

{tradesOpen ? (
<Posts
filteredPosts={filteredPosts}
toggleLoader={toggleLoader}
getMorePosts={getMorePosts}
/>
<Posts filteredPosts={filteredPosts} toggleLoader={toggleLoader} />
) : tradesOpen == false ? (
<TradesClosed />
) : (
Expand Down
Loading