Reputation: 433
I have an API call using axios in the form of:
Service.get('path/to/api',
(status, data) => {
this.setState({ ComponentData: data, loaded: true});
});
{this.state.loaded && <Component id={this.state.ComponentData.id}
prop1={this.state.ComponentData.prop1}
prop2={this.state.ComponentData.prop2.propVal} />
}
The problem I am having is that if a field is null/empty in mongoDB, it isn't returned at all in the response data. Because of this, if prop2 either is an object or is empty, this will throw an error and break with Uncaught TypeError: Cannot read property 'propVal' of undefined.
What is the best way to set up props to handle this issue? Is this something that has to be dealt with on the API side?
Upvotes: 0
Views: 41
Reputation: 1465
There is also an interesting method from Lodash
- _get
It basically tries to access the nested property, and if it's not possible fails silently. You can also provide a default value to return, in case you cannot access the nested property.
After including the method into your component, you could write something like
...
prop2=_get(this.state, 'ComponentData.prop2.propVal', undefined)
...
Upvotes: 0
Reputation: 219
You can use the following kind of the 'prop2' value checking:
const { id, prop1, prop2 } = this.state.ComponentData;
{this.state.loaded && <Component
id={id}
prop1={prop1}
prop2={prop2 ? prop2.propVal : undefined}
/>
}
Upvotes: 1