Let me avoid wasting more time and quickly jump on the problem statement.
What is the problem statement -
- I want to use the same React component both for Create/Update.
How I achieved it -
- Firstly for new object, it worked smoothly and I wanted to reuse the same component again for edit/update too.
- I sent the existing values as props and saved them into the corresponding states.
- I reused the existing method (axios server call) so that it dynamically POST/PUT as needed.This is show below -
//this method calls post/put dynamically - simple code here..no rocket science
methodCall = () => {
const { Id, editable, details } = this.state;
//check if new or existing record
if (editable) {
return API.put(`/post/${Id}`, details);
} else {
return API.post("/post", details);
}
};
//call this method onClick/onSubmit - as you want to
handleSubmit = (event) => {
event.preventDefault();
//call dynamic
this.methodCall()
.then((response) => {
//handle success
})
.catch(function (error) {
// handle failure
});
};
Comments