add infinite scroll

This commit is contained in:
Fran
2026-01-15 19:17:28 -03:00
parent 3a5994d13a
commit 6d08a0985b
4 changed files with 138 additions and 61 deletions

View File

@@ -1,17 +1,21 @@
import { apiBase } from "@/stores/url"; import { apiBase } from "@/stores/url";
import { sesionStore } from "@/stores/usuario"; import { sesionStore } from "@/stores/usuario";
import { get } from "svelte/store"; import { get } from "svelte/store";
import type { Post } from '../../types';
import { PAGE_SIZE } from '../stores/posts';
export async function getPosts() { export async function getPosts(page: number = 1): Promise<Post[]> {
const token = get(sesionStore)?.accessToken;
const headers: HeadersInit = {};
if (token) headers.Authorization = `Bearer ${token}`;
const req = await fetch(`${get(apiBase)}/timeline?pageSize=20`,{ const res = await fetch(
headers: { `${get(apiBase)}/timeline?page=${page}&pageSize=${PAGE_SIZE}`,
Authorization: `Bearer ${get(sesionStore)?.accessToken}` { headers }
);
} if (!res.ok) throw new Error('Error cargando posts');
});
if (req.ok) { return res.json();
return await req.json(); }
}
}

View File

@@ -0,0 +1,32 @@
import { get } from 'svelte/store';
import { page, loadingPosts, PAGE_SIZE } from '@/stores/posts';
import { appendPosts } from '@/stores/posts';
import { getPosts } from './getPosts';
let finished = false;
export async function loadMorePosts() {
if (get(loadingPosts) || finished) return;
loadingPosts.set(true);
try {
const currentPage = get(page);
const newPosts = await getPosts(currentPage);
if (newPosts.length === 0) {
finished = true;
return;
}
appendPosts(newPosts);
if (newPosts.length < PAGE_SIZE) {
finished = true;
} else {
page.update(p => p + 1);
}
} finally {
loadingPosts.set(false);
}
}

View File

@@ -1,29 +1,42 @@
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import type { Post } from '../../types'; import type { Post } from '../../types';
export const posts = writable<Post[] | undefined>(undefined); export const posts = writable<Post[]>([]);
export const loadingPosts = writable(false);
export const page = writable(1);
export const PAGE_SIZE = 20;
export const setPosts = (newPosts: Post[]) => { export const setPosts = (newPosts: Post[]) => {
posts.set(newPosts); posts.set(newPosts);
}; };
export const addPost = (post: Post) => { export const appendPosts = (newPosts: Post[]) => {
posts.update((currentPosts) => [post, ...currentPosts]); posts.update((current) => [...current, ...newPosts]);
}; };
export const updatePostStore = (postId: string, updatedData: Partial<Post>) => { export const addPost = (post: Post) => {
posts.update((currentPosts) => posts.update((current) => [post, ...current]);
currentPosts.map((post) => (post.id === postId ? { ...post, ...updatedData } : post)) };
export const updatePostStore = (
postId: string,
updatedData: Partial<Post>
) => {
posts.update((current) =>
current.map((post) =>
post.id === postId ? { ...post, ...updatedData } : post
)
); );
}; };
export const removePost = (postId: string) => { export const removePost = (postId: string) => {
posts.update((currentPosts) => { posts.update((current) =>
const a = currentPosts.filter((post) => post.id !== postId); current.filter((post) => post.id !== postId)
return a; );
});
}; };
export const resetPosts = () => { export const resetPosts = () => {
posts.set(undefined); posts.set([]);
page.set(1);
}; };

View File

@@ -1,56 +1,71 @@
<script lang="ts"> <script lang="ts">
import { goto, replaceState } from '$app/navigation'; import { replaceState } from '$app/navigation';
import { page } from '$app/state';
import { onMount } from 'svelte';
import Card from '@/components/ui/card/card.svelte'; import Card from '@/components/ui/card/card.svelte';
import { Content } from '@/components/ui/card'; import { Content } from '@/components/ui/card';
import { sesionStore } from '@/stores/usuario';
import CrearPost from '@/components/crear-post.svelte';
import { posts, resetPosts, setPosts, updatePostStore } from '@/stores/posts';
import PostCard from '@/components/PostCard.svelte';
import type { Post } from '../types';
import ModalEditar from './[perfil]/modalEditar.svelte';
import { updatePost } from '@/hooks/updatePost';
import { fade, slide } from 'svelte/transition';
import { getPosts } from '@/hooks/getPosts';
import Spinner from '@/components/ui/spinner/spinner.svelte'; import Spinner from '@/components/ui/spinner/spinner.svelte';
import { page } from '$app/state';
import Dialog from '@/components/ui/dialog/dialog.svelte'; import Dialog from '@/components/ui/dialog/dialog.svelte';
import DialogContent from '@/components/ui/dialog/dialog-content.svelte'; import DialogContent from '@/components/ui/dialog/dialog-content.svelte';
import CrearPost from '@/components/crear-post.svelte';
import PostCard from '@/components/PostCard.svelte';
import ModalEditar from './[perfil]/modalEditar.svelte';
import { sesionStore } from '@/stores/usuario';
import {
posts,
updatePostStore,
loadingPosts
} from '@/stores/posts';
import { updatePost } from '@/hooks/updatePost';
import { loadMorePosts } from '@/hooks/loadMorePosts';
import type { Post } from '../types';
import { fade, slide } from 'svelte/transition';
$effect(() => { let postAModificar: Post | null = null;
resetPosts(); let mensajeError = '';
(async () => { let sentinel: HTMLDivElement;
setPosts(await getPosts());
})(); onMount(() => {
loadMorePosts();
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
loadMorePosts();
}
},
{ rootMargin: '200px' }
);
observer.observe(sentinel);
return () => observer.disconnect();
}); });
let postAModificar: Post | null = $state(null);
let mensajeError = $state('');
async function handleEditar(e: SubmitEvent) { async function handleEditar(e: SubmitEvent) {
e.preventDefault(); e.preventDefault();
if (postAModificar == null) return; if (!postAModificar) return;
await updatePost( await updatePost(
postAModificar, postAModificar,
(postnuevo: Post) => updatePostStore(postAModificar!.id, postnuevo), (postNuevo: Post) =>
updatePostStore(postAModificar!.id, postNuevo),
mensajeError mensajeError
); );
postAModificar = null; postAModificar = null;
} }
let from = $state(page.url.searchParams.get('from'));
$effect(() => { let from = page.url.searchParams.get('from');
goto('/', { replaceState: true });
}); if (from) {
replaceState('/', {});
}
</script> </script>
{#if from == 'cambio_contraseña'} {#if from === 'cambio_contraseña'}
<Dialog <Dialog open>
open={true} <DialogContent>
onOpenChange={() => { Se cambió la contraseña del usuario exitosamente
from = ''; </DialogContent>
}}
>
<DialogContent>Se cambio la contraseña del usuario exitosamente</DialogContent>
</Dialog> </Dialog>
{/if} {/if}
@@ -65,22 +80,25 @@
<div class="flex min-h-fit w-full items-center justify-center p-6 md:p-10"> <div class="flex min-h-fit w-full items-center justify-center p-6 md:p-10">
<div class="w-full max-w-6xl"> <div class="w-full max-w-6xl">
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
{#if $sesionStore !== null} {#if $sesionStore}
<CrearPost /> <CrearPost />
{/if} {/if}
<hr /> <hr />
{#if $posts === undefined} {#if $posts.length === 0 && $loadingPosts}
<Card> <Card>
<Content class="flex items-center justify-center gap-2"> <Content class="flex items-center justify-center gap-2">
<Spinner class="h-10 w-10" /> <Spinner class="h-10 w-10" />
<p>Cargando</p> <p>Cargando</p>
</Content> </Content>
</Card> </Card>
{:else if $posts.length <= 0}
{:else if $posts.length === 0}
<Card> <Card>
<Content> <Content>
<p class=" text-center leading-7 not-first:mt-6">No hay Posts que mostrar</p> <p class="text-center leading-7">
No hay Posts que mostrar
</p>
</Content> </Content>
</Card> </Card>
{:else} {:else}
@@ -91,10 +109,20 @@
{/each} {/each}
{/if} {/if}
</div> </div>
<div bind:this={sentinel} class="h-1"></div>
{#if $loadingPosts && $posts.length > 0}
<div class="flex justify-center py-4">
<Spinner />
</div>
{/if}
</div> </div>
</div> </div>
{#if postAModificar} {#if postAModificar}
<div in:fade> <div in:fade>
<ModalEditar callbackfn={handleEditar} bind:post={postAModificar} /> <ModalEditar
callbackfn={handleEditar}
bind:post={postAModificar}
/>
</div> </div>
{/if} {/if}