Home > other >  How to organize two api calls when clicking save button in the formik form
How to organize two api calls when clicking save button in the formik form

Time:09-24

Let's say we have one form with the save button. One patch api call to save most of fields filled by users when clicking save button. However, we have one checkbox field in the form which needs another api to check the user permission and also save the selection from the user when clicking the save button along with other fields.

For example:

Sequence 1 PATCH api/1

• If this API calls successfully, then update some fields to database. Then continue to call sequence 2 API

Sequence 2 PATCH api/2

• If this API call return an error, then stop calling the next API, and UI returns an error/warning message. Indicates unsuccessful update & save, this misled user because a portion of data has already been saved to database.

• Also, in some fields once value has already been updated to the database. UI will update screen to read-only mode to prevent user updating those fields. This could lead to confusion if there is warning message in UI that indicates unsuccessful update & save.

Sequence 3 PATCH api/3

CodePudding user response:

I suggest you put the second call to the api inside of .then after the first api call. This way, if the first api fails, 1 error will appear and the client will go after resolving that. Otherwise if you try to call them separately, if the first one fails, it goes to the second one and if that fails too, there will be two errors to be shown to the client, which does not sound user-friendly.

CodePudding user response:

Another way to handle this, would be using async-await inside the handleSave function somewhat like this pseudo-javascript code:

const handleSave = async () => {

    // First API call related to the checkbox
    let response = await fetch("apiroute/first-call", { /* ... */ });
    
    // Check if the api call has given an error (this should be adapted to the actual server response returned by your APIs)
    if (!response.ok) {
        // handle the error related to the checkbox (this is just an example)
        setError("You don't have the permission to check this box");
        
        // stop the function here
        return;
    }

    // Second API call
    let response = await fetch("apiroute/second-call", { /* ... */ });

    if (!response.ok) {
        // handle second error related to the fields (also, this is just a minimal example)
        setError("There was some error in the submitted fields");
    }
}
  • Related