Reputation: 528
When I click the edit form, I am checking the form status. In the edit, status='Draft'. If status is draft, button is disabled.
<Button className="btn btn-primary" disabled={location.state.status == 'Draft'} type="button" onClick={() => saveAsDraftInvoice(values)}>
<i className="mdi mdi-table-edit"></i> Save as Draft
</Button>
Above code is working well. button is disabled correctly. But when i go to add new record, error said "
TypeError: Cannot read property 'status' of undefined"
reason is, when I edit form, status is have inside the object. When I go to save new record that 'status' undefine. how I fix this issue
Upvotes: 1
Views: 412
Reputation: 1
You can use optional chaining on the location object as below!
disabled={location?.state?.status == 'Draft'}
Upvotes: 0
Reputation: 36
For instance just check if status
property exists.
It can be done with additional condition:
location.state && location.state.status == 'Draft'
or with optional chaining:
location.state?.status == 'Draft'
<Button className="btn btn-primary" disabled={location.state && location.state.status == 'Draft'} type="button" onClick={() => saveAsDraftInvoice(values)}>
<i className="mdi mdi-table-edit"></i> Save as Draft
</Button>
or
<Button className="btn btn-primary" disabled={location.state?.status == 'Draft'} type="button" onClick={() => saveAsDraftInvoice(values)}>
<i className="mdi mdi-table-edit"></i> Save as Draft
</Button>
Upvotes: 1
Reputation: 3722
You can check if the object exists every step of the way to prevent trying to access an undefined value:
disabled={location && location.state && location.state.status == 'Draft'}
If location or state aren't defined the disabled
prop will be false.
Upvotes: 1