How to prevent a React app crashes when an object is passed as null

I have in my React app a situation where an object called site is passed as a null object.
This provokes the app to crash and I don’t know how to handle this. The site object can be null in specific situations so I have to not let the app crash when a null object comes.

I have this example

const Sites = ({
  isOpen,
  onClose,
  site,
  onChange: onChangeSelectedSite = () => {},
}) => {
  
  <CODE>
  const preparedSites = useMemo(
    () =>
      sites
        .sort(sortSiteSelection(site))
        .map(elm => {
          const arr = [
            elm.siteId,
            elm.city,
            elm.state,
            elm.country,
            elm.address,
            elm.status,
          ];
          if (nearestSites.length)
            arr.push(
              nearestSites.find(s => s.closestSiteId === elm.siteId).distance,
            );
          return arr;
        })
        .sort((a, b) => a[6] - b[6]),
    [sites, site, nearestSites],
  );
  
  <code>

}

The above code is what receive site ad on that line .sort crashes as site === null.

The site is passed from the following parent

const SitesChangeButton = ({ site, onChange }) => {
  <code>
  <Sites
        site={site}
        isOpen={isOpenNew}
        onClose={onCloseNew}
        onChange={onChange}
      />
}

The site object when present have

{
   siteId,
   city,
   state,
   country,
   address,
   status,
}

When an object is null as obvious we have errors as the above items are null like status is null as an example.

If it is necessary to show more details let me know in the comments

Adding the sort functionality with the suggested fix but still not working

import { pipeSort } from '../fp';

const nameCompare = (x, y) => x.name.localeCompare(y.name);
const cityCompare = (x, y) => x.city.localeCompare(y.city);
const compareCountry = s => (x, y) => {
  if (!s) return 0;

  if (x.countryCode === s.countryCode && y.countryCode === s.countryCode)
    return 0;
  else if (x.countryCode === s.countryCode) return -1;
  else if (y.countryCode === s.countryCode) return 1;
  else return x.countryCode.localeCompare(y.countryCode);
};

export const sortSiteSelection = selectedSite => {
  if (!selectedSite) {
    console.log('NULL FROM SORT SITE');
    return 0;
  }
  pipeSort(compareCountry(selectedSite), nameCompare, cityCompare);
};

4 thoughts on “How to prevent a React app crashes when an object is passed as null”

  1. How you’d handle null entirely depends on what you want the component to do when the value is null. For example, if the <Sites/> component shouldn’t render at all, you’d indicate that:

    const SitesChangeButton = ({ site, onChange }) => {
      <>
        {site &&
          <Sites
            site={site}
            isOpen={isOpenNew}
            onClose={onCloseNew}
            onChange={onChange}
          />
        }
      </>
    }
    

    Or perhaps you’d display the component but have it internally handle null, such as returning null for preparedSites:

    const preparedSites = useMemo(
      () => site ?
        sites.sort.....
        : null,
      [sites, site, nearestSites],
    );
    

    Or perhaps you’d handle null within sortSiteSelection (wherever that’s defined), something like:

    if (site === null) {
      return 0; // all values have the same sort result
    }
    

    Basically, and I guess this is a very generic statement for programming in any language anywhere… Wherever you want your logic for handling null to be, and whatever you want that logic to be, that’s what you’d write in the code.

    Reply

Leave a Comment