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);
};

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

Leave a Comment