In my this API I wanted to take the values from the recommended configurations but some values are null, so my application gives me an error:
null is not an object
Here is my code:
let page1 = this.state.dataSource1.map((val, key) => {
// if (val.platforms[0].requirements_en.minimum != null) {
// }
return (
{val.platforms[0].requirements_en.recommended ==! null ?
<Text style={styles.name}>minimal configuration : {val.platforms[0].requirements_en.recommended}</Text>
:
<Text>Nothing</Text>
}
)
})
I wanted to say that if the value is not null, send me the data otherwise a simple text but it does not work...
You have got a few issues in your code.
Firstly, you are returning an object, but you don't specify a key.
So you either need to add one, or more likely this is an error and you need to remove the curly braces in your return
.
Secondly, you have got a typo ==!
instead of !==
.
Thirdly, about your question you need to check that every element returned by the API exists with the optional chaining operator like so: val?.platforms[0]?.requirements_en?.recommended
To expand on this a bit, the optional chaining operator will return undefined
if the part before the ?.
is null
or undefined
.
In your case, sometimes requirements_en
is null hence why you got your error.
let page1 = this.state.dataSource1.map((val, key) => {
return val?.platforms[0]?.requirements_en?.recommended ? (
<Text key={key}>
minimal configuration: {val.platforms[0].requirements_en.recommended}
</Text>
) : (
<Text>Nothing</Text>
)
})