9

In my React App I'm getting an error in the sort functionality

Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'

I have no idea what the problem is and the functionality is this:

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],
    );

The error happening on the .sort part and the ´sortSiteSelection´ is as follow

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

The OBJ of site is just

{
 siteId,
 city,
 elm.state,
 country,
 address,
 status,

}

1 Answer 1

30

I would say it's because the array is in strict mode. You should create a copy of this array. There are multiple ways for that.

[...sites].sort(sortSiteSelection(site))

or

sites.slice().sort(sortSiteSelection(site))

I hope this solves the issue you're facing

Sign up to request clarification or add additional context in comments.

2 Comments

I tried both ways but still have this issue Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]' at Array.sort (<anonymous>)
Error was fixed somehow was an error in different places where other sorts where used and adding this fixed the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.