From 3bae06ab0c6c5d1c4b74e82c7395077994ffa476 Mon Sep 17 00:00:00 2001 From: Bart van den Aardweg Date: Mon, 21 Jun 2021 16:33:58 +0200 Subject: [PATCH] fix(image): only observe io of element exists --- example/src/pages/unmounttest.tsx | 78 +++++++++++++++++++ .../createIntersectionObserver.test.tsx | 16 ++++ src/image/createIntersectionObserver.ts | 4 + 3 files changed, 98 insertions(+) create mode 100644 example/src/pages/unmounttest.tsx diff --git a/example/src/pages/unmounttest.tsx b/example/src/pages/unmounttest.tsx new file mode 100644 index 0000000..9563a41 --- /dev/null +++ b/example/src/pages/unmounttest.tsx @@ -0,0 +1,78 @@ +import React, { useEffect, useState } from 'react'; +import { GetStaticProps } from 'next'; +import { Box, Text, Flex } from 'rebass'; +import SbEditable from 'storyblok-react'; +import { sdk } from '~/lib/graphqlClient'; +import { WithStoryProps, useStory, Image } from '@storyofams/storyblok-toolkit'; + +type GalleryProps = WithStoryProps; + +const Gallery = ({ story: providedStory }: GalleryProps) => { + const storyProp = useStory(providedStory); + + const [story, setStory] = useState(storyProp); + + useEffect(() => { + setStory(null); + }, []); + + return ( + + + Gallery + + {!!story && ( + + + {story?.content?.images?.map((image) => ( + + + + + + ))} + + + )} + + ); +}; + +export default Gallery; + +export const getStaticProps: GetStaticProps = async () => { + let story; + let notFound = false; + + try { + story = (await sdk.galleryItem({ slug: 'gallery' })).GalleryItem; + } catch (e) { + notFound = true; + } + + return { + props: { + story, + }, + notFound, + // revalidate: 60, + }; +}; diff --git a/src/image/__tests__/createIntersectionObserver.test.tsx b/src/image/__tests__/createIntersectionObserver.test.tsx index 8e018f7..8b38e07 100644 --- a/src/image/__tests__/createIntersectionObserver.test.tsx +++ b/src/image/__tests__/createIntersectionObserver.test.tsx @@ -153,4 +153,20 @@ describe('[image] createIntersectionObserver', () => { expect(optionsMock).toHaveBeenLastCalledWith({ rootMargin: '1250px' }); }); + + it('should not observe if target doesnt exist', async () => { + const callbackMock = jest.fn(); + const component =
; + + act(() => { + render(component); + }); + + const result = await createIntersectionObserver( + document.querySelector('#notexistant'), + callbackMock, + ); + + expect(result).toBeNull(); + }); }); diff --git a/src/image/createIntersectionObserver.ts b/src/image/createIntersectionObserver.ts index 32362ef..25e40d7 100644 --- a/src/image/createIntersectionObserver.ts +++ b/src/image/createIntersectionObserver.ts @@ -38,6 +38,10 @@ export const createIntersectionObserver = async ( }, ); + if (!el) { + return null; + } + // Add element to the observer io.observe(el);