Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot destructure property `name` of 'undefined' or 'null'

Object destructuring throws error in case of null object is passed

function test ({name= 'empty'}={}) {
  console.log(name)
}
test(null);

Uncaught TypeError: Cannot destructure property name of 'undefined' or 'null'. at test (:1:15) at :1:1

like image 374
rahlrokks Avatar asked Feb 18 '19 10:02

rahlrokks


2 Answers

See the docs:

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

In other words, the default parameter will not be assigned if null gets passed:

function fn(arg = 'foo') {
  console.log(arg);
}
fn(null);

Destructure in the first line of the function instead:

function test (arg) {
  const { name = 'empty' } = arg || {};
  console.log(name)
}
test(null);
like image 105
CertainPerformance Avatar answered Nov 16 '22 06:11

CertainPerformance


If you don't have any arguments or a value assigned to the object,but want to pass it empty because you plan on assigning it a value at a later stage,Its best to pass it empty by not placing it inside parenthesis.

So lets suppose you have :

This function :

const {signup}  = useAuth()

This will definitely throw an error because you are essentially passing the object with no arguments.

To fix this,you would have to remove the empty object from parenthesis as follows:

const signup  = useAuth() 

then use it in your class or function thereafter as follows:

async {....
     await signup(emailRef.current.value, passwordRef.current.value)

...}
like image 1
RileyManda Avatar answered Nov 16 '22 08:11

RileyManda