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

add useStatic helper to inline results of API calls #79

Merged
merged 18 commits into from
May 30, 2020
Merged

Conversation

danielroe
Copy link
Member

@danielroe danielroe commented May 27, 2020

useStatic

You can now statically generate expensive functions using useStatic.

Static generation

If you are generating the whole app (or just prerendering some routes with nuxt build && nuxt generate --no-build) the following behaviour will be unlocked:

  • On generate, the result of a useStatic call will be saved to a JSON file and copied into the /dist directory.
  • On hard-reload of a generated page, the JSON will be inlined into the page and cached.
  • On client navigation to a generated page, this JSON will be fetched - and once fetched it will be cached for subsequent navigations. If for whatever reason this JSON doesn't exist, such as if the page wasn't pre-generated, the original factory function will be run on client-side.

See the deployed fixture.

SSR

If the route is not pre-generated (including in dev mode), then:

  • On a hard-reload, the server will run the factory function and inline the result in nuxtState - so the client won't rerun the API request.
  • On client navigation, the client will run the factory function.

In both of these cases, the return result of useStatic is a null ref that is filled with the result of the factory function or JSON fetch when it resolves.

import { defineComponent, useContext, useStatic, computed } from 'nuxt-composition-api'
import axios from 'axios'

export default defineComponent({
  setup() {
    const { params } = useContext()
    const id = computed(() => params.value.id)
    const post = useStatic(
      id => axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`),
      id,
      'posts'
    )

    return { post }
  },
})

@vercel
Copy link

vercel bot commented May 27, 2020

This pull request is being automatically deployed with Vercel (learn more).
To see the status of your deployment, click below or on the icon next to each commit.

🔍 Inspect: https://vercel.com/nuxt-community/composition-api/526xn869v
✅ Preview: https://composition-api-git-use-static.nuxt-community.now.sh

@danielroe danielroe merged commit 88b37c3 into master May 30, 2020
@danielroe danielroe deleted the use-static branch May 30, 2020 21:56
src/index.ts Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants