Search code examples
javascriptreactjscreate-react-appfirebase-hostingoptional-chaining

optional chaining operator working on local host but not in production


I'm not sure if this something I'm doing wrong, or that I missing something, But I've added in optional chaining ?. to some of the parts of my create react app. i.e

  const customFieldName = customFields[0]?.customFieldName || "Custom Field";

This works on localhost in chrome on my mac, and also on the Xcode ios 13 iPad simulator in Safari but when I deploy the firebase app using

react-scripts build && firebase deploy

The app crashes saying that customFieldName is undefined, which in some cases it will be as the array customFields will be empty/null, but I take care of that my falling back to the "Custom Field" String to be set as default.

So my question is why does the optional chaining ?. code work in local host and not in deployment? I have checked to see that browser in loading the lastest version, which it is.

I'm also aware that optional chaining ?. is a new feature therefore may not work on all browser and especially older versions.

I would appreciate any help.

I'm thinking it could be impossible to know in future if the code is actually working in production when it works in development/localhost.


Solution

  • It appears that your value that is expected to be the actual array is actually null or undefined. To prevent the error there are two courses of action you can take:

    1. ensure the array is never null or undefined (via default arguments or other means)
    2. use optional chaining syntax on the array itself:
    const customFieldName = customFields?.[0]?.customFieldName || "Custom Field";
    //                                  ^ optional chaining added here
    

    Regarding browser support, as long as you are using a proper babel configuration for the feature, or in your case create-react-app >=3.3.0, you should have no issues with browser support. Babel will just transpile the new syntax to valid, cross-browser code, like this:

    var _customFields, _customFields$;
    
    var customFieldName = ((_customFields = customFields) === null || _customFields === void 0 ? void 0 : (_customFields$ = _customFields[0]) === null || _customFields$ === void 0 ? void 0 : _customFields$.customFieldName) || "Custom Field";