antfu-collective / vite-ssg

Static site generation for Vue 3 on Vite

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fetch API data only on build?

crankysparrow opened this issue · comments

I'm trying to use vite-ssg with an external CMS and fetch data from the CMS only on build, but not again on the client side when the page is loaded. I believe this is discussed in this issue, and the proposed solution looks like this:

import axios from 'axios'
const { get } = axios

// The data we will show
const repo = ref<RepoData | null>(null)

// A function to get the data
const fetch = async() => {
  const data = await get(`https://api.github.com/repos/nickgraffis/petite-vin`)
  repo.value = data.data
}

// Only run this function client side if we don't have a value assigned to repo yet
// if repo already has a value, it was fetched during build
if (!repo.value) fetch()

// During the build, fetch the data before building the component
onServerPrefetch(async() => {
  await fetch()
})

This works in that it does fetch data at build time, and inserts it into the HTML. But the API is still called again in the browser.

Is there any way around this or would I need to use a framework like Nuxt to achieve what I'm looking for?

onServerPrefetch only useful in SSR mode,
you should check repo is null in onMounted,
if rep is null , that is SSR , you should not call fetch in onMounted