0

I'm using Inertia.js + Vue 3 for Server-Side Rendering (SSR). In certain cases, I want to pre-fetch and set data during server-side rendering.

<template>
  data: {{myData}}
</template>
<script setup>
import {ref} from "vue";

const isServer = typeof window === 'undefined'
const myData = ref(null)

if (isServer) {
  console.log('on server')
  myData.value = 'data from server'
} else {
  console.log('on client')
  if (myData.value === null) {
    myData.value = 'data is null'
  }
}
</script>

Both console logs are visible. However, in the browser, myData initially displays as 'Data from the server' but quickly changes to 'Data is null'. When I check the page source, myData is rendered as 'Data from the server'.

Does this mean that the const myData gets redefined as null when the browser renders the page? Is this normal behavior, and does it imply that prefetching data while rendering on the server is not possible?

My expectation is that if the page is rendered on the client, it should display skeletons and perform a partial reload. But if the page is rendered on the server, it should fully render without a partial reload.

Any insights or solutions would be greatly appreciated. Thank you!

1 Answer 1

-1

Try below:

<template>
  <div>
    <p>Data: {{ isServer ? 'data from server' : myData }}</p>
    <button v-if="!isServer" @click="partialReload">Partial Reload</button>
  </div>
</template>

<script setup>
  import { ref } from 'vue';

  const isServer = typeof window === 'undefined';
  const myData = ref(null);

  if (!isServer && myData.value === null) {
    myData.value = 'data is null';
  }

  function partialReload() {
    // Implement your partial reload logic here
    // For example, you can use location.reload() to reload the page partially
    location.reload();
  }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thank you for your response. But still, myData initially displays as 'Data from the server' and quickly changes to 'Data is null'. Upon inspecting the page source, it indeed shows 'data ifrom server' The server rendering is behaving as expected, but it seems that myData is being redefined as null in the browser, triggering the condition if (!isServer && myData.value === null).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.