Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

arrrssssss's avatar

Problem with multi use of Inertia::Optional Prop with WhenVisible

Hi lads,

In my Vue component I try to load a property as an optional, and use InertiaJS WhenVisible component to lazy load it, this property used in multiple part of my component HTML, for example in this code block I lazy load property named details, but in the last part of code I want to access that loaded details, I face error and have to write another WhenVisible to load it via backend again, and it make mass request, is there any solution for it ? ** Note that I looked for a solution without custom API, axios request and something like this **

	<div class="container flex flex-col gap-y-6 lg:gap-y-8">
        <WhenVisible data="details">
            <template #fallback>
                Loading...
            </template>
            <div class="hidden lg:flex flex-col mt-6">
                <h1 class="text-lg font-medium text-dark-900">{{ details.title }}</h1>
            </div>
            <div class="hidden lg:block">
                <component :is="comp1" :values="details"/>
            </div>
        </WhenVisible>

		<!--Some other elements are here-->

        {{ details.description }}
    </div>
0 likes
1 reply
LaryAI's avatar
Level 58

Certainly! The issue here is that the WhenVisible component from Inertia.js only provides the lazy-loaded prop (details) within its slot scope. Outside of the WhenVisible block, details is still undefined unless you trigger another request, which leads to multiple backend calls and inefficiency.

How to solve this:

You want to load details only once (when it becomes visible), and then use it anywhere in your component without triggering additional requests. The best approach is to capture the loaded details in a local reactive variable when it first loads, and then use that variable throughout your component.

Here's how you can do it in Vue (assuming Vue 3 with <script setup> syntax):



Explanation:

  • We declare a ref called details to store the loaded data.
  • Inside the WhenVisible slot, when details is loaded, we assign it to our local details ref (using a little trick with <span v-if="details = loadedDetails"></span> to set it reactively).
  • Now, anywhere else in your template, you can use details without triggering another backend request.
  • This avoids the need for custom API calls or multiple WhenVisible components.

Note:
If you are using Vue 2 with the Options API, you can use data() and this.details instead, but the concept is the same: cache the loaded data in a variable accessible to the whole component.


Summary:
Cache the lazy-loaded prop in a local variable when it first loads, then use that variable everywhere else in your component. This avoids multiple backend requests and keeps your code efficient and clean.

Please or to participate in this conversation.