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

Fetch API data only on build? #352

Open
crankysparrow opened this issue May 26, 2023 · 1 comment
Open

Fetch API data only on build? #352

crankysparrow opened this issue May 26, 2023 · 1 comment

Comments

@crankysparrow
Copy link

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?

@Eacolt
Copy link

Eacolt commented Jul 2, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants