lancegliser/netflix-react-apollo

Needs updated with IntersectionObserver integration

lancegliser opened this issue · 1 comments

Recent work I completed has made vertical and horizontal observations for lazy loading the images functional. Need to get that merged in.

Base idea:

  const [element, setElement] =
    useState<CompactSuggestionItemProps["element"]>(null);

  // Node images are base64 encoded, if you request it, you've already loaded it.
  // Setup an intersection observer to watch position and load display images as items are paged
  const [getDisplayImage, nodeDisplayImageQuery] =
    useDisplayImageUrlLazyQuery({
      // If pulled into the cache, it crashes the browser
      fetchPolicy: "no-cache",
    });
  const intersectionObserver = useMemo(
    () =>
      new IntersectionObserver(
        (entries, observer) => {
          if (!entries.at(0)?.isIntersecting) {
            return;
          }
          observer.disconnect();

          if (
            // Already included, skip it
            props.displayImageUrl ||
            // Nothing to request, skip it
            !props.nodeId
          ) {
            return;
          }

          getDisplayImage({
            variables: {
              id: props.nodeId!,
            },
          });
        },
        {
          rootMargin: "-30px 0px 0px -30px",
          threshold: 0.02,
        },
      ),

    [getDisplayImage, props.displayImageUrl, props.nodeId],
  );
  useLayoutEffect(() => {
    if (!element) {
      return;
    }

    intersectionObserver.observe(element);
    return () => {
      intersectionObserver.disconnect();
    };
  }, [intersectionObserver, element]);

Closed with #3