How to create Infinite Scroll with Svelte

Intersection observer with Svelte

Component in svelte

<script>
import axios from "axios";
import { infiniteScroll } from "../../functions/infiniteScroll";

let pageNumber = 0;
let characters = [];
let Loading = false;

const fetchData = async () => {
try {
Loading = true;
const response = await axios({
method: "GET",
url: "https://rickandmortyapi.com/api/character/",
params: { page: pageNumber },
});
// SAVE NEW RESULTS
characters = [
...new Set([...characters, ...response.data.results.map((b) => b)]),
];
Loading = false;
} catch (error) {
console.log(error);
}
};
const load = () => {
setTimeout(() => {
pageNumber = pageNumber + 1;
fetchData();
}, 300); // WE WAITED A FEW SECONDS
};
// REACTIVE DECLARATIONS
let elementRef = null;
$: {
if (elementRef) {
infiniteScroll({ fetch: load, element: elementRef });
}
}
</script>

<div class="box-shawdow">
{#each characters as character}
<div class="grid-games">
<div class="box-game">
{character.name}
</div>
</div>
{/each}

{#if Loading}
<h1>Cargando...</h1>
{/if}
<!-- ELEMENT OBSERVER -->
{#if Loading === false}
<li bind:this={elementRef}>Cargando</li>
{/if}
</div>

Function of Intersection Observer

export const infiniteScroll = ({ fetch, element }) => {
if (element) {
const observer = new IntersectionObserver(
(entries) => {
const first = entries[0];
if (first.isIntersecting) {
console.log("Is Intersecting");
fetch();
}
},
{ threshold: 1 }
);
observer.observe(element);//Element of DOM
}
};

Frontend Developer and Content Creator from El Salvador

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Callback Functions Across Multiple React Components Based on the Same Event Listener

9 Array Methods Every JavaScript Developer Should Know

How to send data using props and destructor props with react.js

what is NgZone in Angular

Chakra-UI and React

Collapsible Accordion Style Nav in React Native with Scrolling

Top 5 JavaScript Libraries for SVG Animation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nelson Hernández

Nelson Hernández

Frontend Developer and Content Creator from El Salvador

More from Medium

Why Ionic Platform Is The First Choice For Mobile Application Development

Middleware Authentication(JWT TOKEN) using hooks in CodeIgniter 3

choochoo.js — A timing library.

How We Made Vite Run in Browser