Skip to content

Instantly share code, notes, and snippets.

@Nivg
Last active November 10, 2023 10:08
Show Gist options
  • Save Nivg/afb1058e1f421b1e0d9db217ea790641 to your computer and use it in GitHub Desktop.
Save Nivg/afb1058e1f421b1e0d9db217ea790641 to your computer and use it in GitHub Desktop.
Svelte component with Astro.Build Endpoints (as API) + SSR
<script lang="ts">
import { onMount } from "svelte";
import SanityImage from "./SanityImage.svelte";
// for testing purposes
const delay = (time: number) => {
return new Promise((res) => {
setTimeout(res, time);
});
};
let productsSize: number = 0;
let products: any = [];
onMount(async function () {
try {
await delay(5000);
const productsResponse = await fetch(`/api/products`);
const productsData = await productsResponse.json();
products = productsData;
} catch (error) {
console.error(error);
}
});
const getProductsSize = async () => {
try {
const productsSizeResponse = await fetch(`/api/productsSize`);
const productsSizeData = await productsSizeResponse.json();
productsSize = productsSizeData;
} catch (error) {
console.error(error);
}
};
getProductsSize();
</script>
{#each products as product}
<div class="w-60 h-24 border-1 rounded-md">
<div class="flex flex-row items-center h-full justify-center space-x-5">
<div class="w-28 h-12 rounded-full">
<SanityImage
imageSource={product.image}
width={100}
title={product.productName}
/>
</div>
<div class="flex flex-col space-y-3">
<div class="w-36 h-6 rounded-md">
{product.productName}
</div>
<div class="w-24 h-6 rounded-md">
{product.description ? product.description : ""}
</div>
</div>
</div>
</div>
{:else}
<!-- Skeleton Mock -->
{#each { length: productsSize } as _, i}
<div class="w-60 h-24 border-1 rounded-md">
<div
class="flex animate-pulse flex-row items-center h-full justify-center space-x-5"
>
<div class="w-28 bg-gray-300 h-12 rounded-full" />
<div class="flex flex-col space-y-3">
<div class="w-36 bg-gray-300 h-6 rounded-md" />
<div class="w-24 bg-gray-300 h-6 rounded-md" />
</div>
</div>
</div>
{/each}
{/each}
@Nivg
Copy link
Author

Nivg commented Nov 10, 2023

Don't forget to call the component using the following, so it will not use SSR:
<Products client:only="svelte" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment