1
votes

I have this React component that renders the Lightbox when clicking on an image from gallery page. And seems to work fine overall, but I found a weird behavior, when I clean all my application site data and go the frist time on the gallery page and click an image I get the next error:

error: uncaughtException: Cannot read property 'zero' of undefined TypeError: Cannot read property 'zero' of undefined

react-hot-loader.development.js:294 TypeError: Cannot read property 'zero' of undefined at t.r.runActions (pathToProject/node_modules/fslightbox-react/index.js:1) at callCallback (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:12490) at commitUpdateQueue (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:12511) at commitLifeCycles (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:19858) at commitLayoutEffects (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:22803) at HTMLUnknownElement.callCallback (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:188) at Object.invokeGuardedCallbackDev (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:237) at invokeGuardedCallback (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:292) at commitRootImpl (pathToProject/node_modules/react-dom/cjs/react-dom.development.js:22541) at unstable_runWithPriority (pathToProject/node_modules/scheduler/cjs/scheduler.development.js:653)

Here is my react component:

const Lightbox = () => {
  const dispatch = useDispatch();
  const { items } = useSelector(state => state.items);
  const { lightboxDialog } = useSelector(state => state.window);
  const sources =
    items?.length > 0 ? items.map(item => item.original) : []; // creates an array of strings with url sources to the images

  return (
      <FsLightbox
        toggler={lightboxDialog?.toggler}
        sources={sources}
        slide={lightboxDialog.slide}
      />
  );
};

Has anyone had this problem before? How do I fix it since even the stack-trace is pretty hard to follow

1

1 Answers

1
votes

This occurred for me because the sources property is not reactive as documented here. The documented fix is to add the key property to the FsLightbox element, since the element will be remounted when the key property is changed.

For this particular scenario, I suspect that setting key to sources.length should address the issue, as follows:

<FsLightbox
  toggler={lightboxDialog?.toggler}
  sources={sources}
  slide={lightboxDialog.slide}
  key={sources.length}
/>