sachinchoolur / lightGallery

A customizable, modular, responsive, lightbox gallery plugin.
https://www.lightgalleryjs.com/
Other
6.55k stars 1.29k forks source link

Next.js Redux-toolkit init dynamicEl fires error #1548

Closed maidnmw closed 11 months ago

maidnmw commented 1 year ago

I`m trying to open dynamic mode when clicking on image in list. I expect dynamic mode with a list of images to open when image is clicked. Images list should store in redux, cause assumed that there are many different images lists on the page.

But when you try to change state with gallery items directly from redux, the following error occurs: TypeError: Cannot add property __slideVideoInfo, object is not extensible.

Issue has been fixed, but the fix looks a bit strange.

Code with issue

const DynamicGallery = () => {
    const dispatch = useDispatch()
    const lightGallery = useRef(null)

    const open = useSelector(state => state.galery.open)
    const items = useSelector(state => state.galery.items)
    const index = useSelector(state => state.galery.activeItemIndex)
    const closeGalery = () => dispatch(galeryActions.closeGalery())

    const [activeItems, setActiveItems] = useState([])

    /** ERROR OCCURES HERE */
    useEffect(() => {
        if (items?.length) {
            setActiveItems(items)
        }
    }, [items])

    /** Init lightGallery */
    const onInit = useCallback((detail) => {
        if (detail) { lightGallery.current = detail.instance }
    }, [])
    /** Update lightGallery */
    useEffect(() => {
        if (!items || !items?.length) return 
        lightGallery.current?.refresh(activeItems)
    }, [activeItems])
    /** Open lightGallery */
    useEffect(() => {
        const length = activeItems?.length || 0
        if (!open) return
        if (!length || !lightGallery.current) return
        if (index < 0 || index > length - 1) return

        lightGallery.current.openGallery(index)
    }, [activeItems])

    const onAfterClose = () => closeGalery()

    return (
        <LightGallery
            onInit={onInit}
            speed={500}
            plugins={[lgZoom, lgThumbnail, lgVideo]}
            dynamic
            dynamicEl={activeItems}
            closeOnTap={false}
            onAfterClose={onAfterClose}
        />
    )
}

FIX

Issue was fixed by creating new array using .map function. setActiveItems([...items]) not working for some reason.

    /** ERROR OCCURRES HERE */
    useEffect(() => {
        if (!items) return
        if (items?.length) {
            setActiveItems(items.map(item => ({ ...item })))
        }
    }, [items])
stale[bot] commented 11 months ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.