Skip to content

[✨] useOnVisible #268

@GrandSchtroumpf

Description

@GrandSchtroumpf

Is your feature request related to a problem?

Currently useVisibleTask$ runs:

  • when the element enters viewport on hard navigation (<a>)
  • when the component is mounted on soft navigation (<Link>)

This means that we cannot rely on it to lazy query data for example, as it'll be trigger eagerly with soft navigation.

Describe the solution you'd like

As qwik loader already has an IntersectionObserver, I think it could trigger a callback when the element is visible.

export const Item = component$(() => {
  useVisibleTask$(() => {
    // Triggered lazily on MPA
    // Triggered eagerly on SPA
  });
  useOnVisible$(() => {
    // Triggered lazily on MPA & SPA
  });
})

Describe alternatives you've considered

Create a local hook for that, but it might be difficult to optimize.

function useOnVisibleQrl(cb: QRL<() => void>, options) {
  const ref = useSignal<HTMLElement>();
  useVisibleTask$(() => {
    const observer = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        if (!entry.isIntersecting) continue;
        cb();
        obserser.disconnect();
      }
    }, options);
    return () => observer.disconnect();
  })
}
const useOnVisible$ = plicit$FirstArg(useOnVisibleQrl);

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions