Skip to content

What is the best way to load page will all data loaded SSR but load page before data when client? #1429

Closed
@babakness

Description

@babakness

Hey guys,

I'm trying to wrap my mind around the best way to do this. So when a user arrives at a page that is server rendered, the data should load all at once. BUT, when the user arrives at a page after load, it should load the page then load the data, so it feels snappy. This is how I'm doing this right now, is the best way to do this in Nuxt?

import axios from 'axios'
const getTemp = async (bool) => {
    try {
      const res = await axios.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=API_KEY')
      return res.data.main.temp
    } catch (e) {
      return 'error'
    }
}
export default {
  async asyncData ({ isStatic, isServer }) {
    return {
      temp: process.server ? await getTemp() : null
    }
  },

  async created(){
    if(!this.temp) {
      this.temp = await getTemp()
    }
  }
}

Basically, I'm using asynData go get the pre-loaded data feel for SSR, but skipping this for client loaded pages. ie process.server ? await getTemp() : null. Then I'm using created to see if the variable is already set (as is the case when SSR) and if not then trigger a data fetch.

Is this the best way to go about this? Is there a better way? Thank you for your feedback.

This question is available on Nuxt.js community (#c1271)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions