'Cannot destructure property of '{}' as it is null

I've updated some legacy code to react 18 (from 17) and react-router-dom 6 (from v4) and for some reason I'm encountering this error on existing code (that was working just fine)

In all my components I access some data like so

const {
  user,
  person,
  loading,
  locale,
  building: { locale: building_locale } = {},
  updateContext,
} = useContext(GlobalContext)

Right here is the console of said context on his initial state, on the render I'm getting the issue below : enter image description here enter image description here

The code works perfectly fine if I'm doing some workaround like this

const {
  user,
  person,
  loading,
  locale,
  building,
  updateContext,
} = useContext(GlobalContext)
const building_locale = building?.locale

But those changes would impact roughly 3k files and I'm really not looking forward to having to execute that kind of regex.

As far as I know, the code is actually working fine and the error makes no sense but maybe someone has any clue as to why this might happen

I would have provided a codepen if I was somehow able to reproduce in a pristine coding environment but this seems to be specific to my app's context, mostly looking for some ideas / rubber ducks 🥲



Solution 1:[1]

There seem to be an issue when building value is null, a workaround is to declare it as undefined instead:

const o1 = { building: { locale: undefined } };  // Works - even with null
const o2 = { building: null };  // Throws
const o3 = { building: undefined };  // Works


const testDestructuring = (obj) => {
  try {
    const { building: { locale: building_locale } = {} } = obj;
    console.log(JSON.stringify(obj),': Destructured with no errors');
  } catch (e) {
    console.log(e);
  }
};

const tests = [o1, o2, o3];
tests.forEach(testDestructuring);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cesare Polonara