timhagn / gatsby-background-image

Lazy-loading React (multi)background-image component with optional support for the blur-up effect.
MIT License
253 stars 49 forks source link

Error when passing a string in getCurrentFromData #146

Closed paolololol closed 3 years ago

paolololol commented 3 years ago

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch gatsby-background-image@1.4.1 for the project I'm working on.

When loading some images, in particular using the GatsbyImageSharpFluid_withWebp fragment, I got this error: TypeError: Cannot use 'in' operator to search for 'tracedSVG' in /static/leasing-hero-7243173125ec92963d5a31594d1cee6b.jpgat EFel.t.getCurrentFromData (ImageUtils.js:76)at t.switchImageSettings (ImageHandling.js:75)at t.n.render (index.js:273)at $o (react-dom.production.min.js:4289)at Jo (react-dom.production.min.js:4280)at Tl (react-dom.production.min.js:6722)at js (react-dom.production.min.js:5696)at Ms (react-dom.production.min.js:5685)at xs (react-dom.production.min.js:5441)at react-dom.production.min.js:2877

Investigating with a debugger, I noticed that sometimes a string is passed in the data parameter of the getCurrentFromData function, in which case the in operator results in a TypeError. Adding this type guard prevents the crash.

Here is the diff that solved my problem:

diff --git a/node_modules/gatsby-background-image/lib/ImageUtils.js b/node_modules/gatsby-background-image/lib/ImageUtils.js
index bbb3e13..9e7853e 100644
--- a/node_modules/gatsby-background-image/lib/ImageUtils.js
+++ b/node_modules/gatsby-background-image/lib/ImageUtils.js
@@ -66,6 +66,10 @@ var getCurrentFromData = function getCurrentFromData(_ref) {
     }) : "";
   }

+  if(typeof data !== 'object') {
+    return "";
+  }
+
   if ((propName === "currentSrc" || propName === 'src') && propName in data) {
     return getUrlString({
       imageString: checkLoaded ? imageLoaded(data) && data[propName] || "" : data[propName],

This issue body was partially generated by patch-package.

timhagn commented 3 years ago

Hi @paolololol,

mkay, strange, when I add your patch to the sources in gbitest & add a breakpoint on return ""; it get's never hit. Could you add a reproduction case for it?

Best,

Tim.

timhagn commented 3 years ago

Hi @paolololol,

gave it another look and as it doesn't change anything (except solving your issue ; ), I added your patch. Check out the just released gbi@1.5.0 : )!

Feel free to close this issue if it should indeed be solved.

Best,

Tim.

github-actions[bot] commented 3 years ago

Hi there! As @timhagn momentarily is the main contributor to this package, this issue has been automatically marked as stale because it has not had any recent activity. It will be closed if no further activity occurs, though we're open to suggestions on how to get more maintainers! Thank you for your contributions : )!