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
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);
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)
...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With