Checking for Undefined In React
What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content
is undefined or not since your body is nested inside it like
componentWillReceiveProps(nextProps) {
if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
}
You need not use type to check for undefined, just the strict operator !==
which compares the value by their type as well as value
In order to check for undefined, you can also use the typeof
operator like
typeof nextProps.blog.content != "undefined"
You can try adding a question mark as below. This worked for me.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps?.blog?.title,
body: nextProps?.blog?.content
})
}
I was face same problem ..... And I got solution by using typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
You must have to use typeof()
to identified undefined
In case you also need to check if nextProps.blog
is not undefined
; you can do that in a single if
statement, like this:
if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
//
}
And, when an undefined
, empty
or null
value is not expected; you can make it more concise:
if (nextProps.blog && nextProps.blog.content) {
//
}