rahlrokks
rahlrokks

Reputation: 501

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

Upvotes: 36

Views: 222871

Answers (4)

Mohammed Alshaer
Mohammed Alshaer

Reputation: 503

function test (user = {}) {
  const defaultName= 'Invalid User Object'
  if(!user?.name) return defaultName
  const {name} = user
  return user
}
test(null);

Upvotes: 0

RileyManda
RileyManda

Reputation: 2641

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)

...}

Upvotes: 1

Otabek Sadiridinov
Otabek Sadiridinov

Reputation: 1

This is what you need:

function doDotsCalculations(el) {
    const height = el.height();
    const {top = 'empty', left = 'empty'} = el.position() || {};
    const res = height + top + 20;

    $(".owl-carousel .owl-dots").css({
        top: `${res}px`,
        left: `${left}px`
    });
}

Upvotes: -5

CertainPerformance
CertainPerformance

Reputation: 371019

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

Upvotes: 49

Related Questions