Home > Blockchain >  How can I make use of the value returned from my API that is expressed in Collections.singletonMap?
How can I make use of the value returned from my API that is expressed in Collections.singletonMap?

Time:11-06

Basically, I'm trying to update the attribute "subscribed_status" from one of the entities when the API is called. When the attribute gets patched/updated successfully or unsuccessfully in my java server, I will get a message in the frontend console accordingly, expressed in the following form due to the use of Collections.singletonMap:

{response: 'FAILURE'},

{response: 'SUCCESS'}

The question is when I get this from the backend, how I can set conditions like the following in my Reactjs?

//The condition doesn't work because data is not string. I'm not even sure
if(res.data==='FAILURE'){
     //execute some sorts of command
}

For a better understanding of what my backend returns to my frontend, the following is provided for review:

@PatchMapping("/updateSubscribedStatus/{email}")
public Map<String, String> updateSubscribedStatus(@PathVariable String email) throws AlreadySubscribedException {
    try{
        Boolean updateStatus=userService.updateSubscribedStatus(email);
        if(updateStatus){
            return Collections.singletonMap("response", "SUCCESS");
        }
        return Collections.singletonMap("response", "FAILURE");
    }catch(Exception alreadySubscribedException){
        return Collections.singletonMap("response", "FAILURE");
    }
}

In my frontend, I am using axios to call the API and invoke a function on the condition that I get {response: 'FAILURE'}:

export const updateSubscribedStatus=(email:string,setSubscribedStatus:(subscribedStatus:boolean)=>void,toggleShowAlreadySubscribedError:()=>void)=>{
axios.patch(`http://localhost:8080/user/updateSubscribedStatus/${email}`)
    .then((res)=>{
        console.log(res.data);
        setSubscribedStatus(true);
        // The following if statement is where I get stuck
        if(res.data.toString()==="FAILURE"){
            toggleShowAlreadySubscribedError();
        }
    }).catch((error)=>{
        console.log(error);
        setSubscribedStatus(false);
})}

I will appreciate your help! Thanks a million in advance!

CodePudding user response:

Without knowing much about axios, it looks to me that res.data will be the full payload, so I expect res.data.response to contain your "FAILURE" string.

Moreover, I do think the correct RESTFul way to implement would be to return "HTTP 200 OK" in case of success and an "HTTP 40x" (say HTTP 409) in case of already subscribed. You can achieve this by putting a ResponseEntity<?> as a return type of your @PathMapping method and returning the correct code.

public ResponseEntity<?> updateSubscribedStatus(...) {
  try {
   ...
   return new ResponseEntity<Success>(HttpStatus.OK);
} catch (..) {
   return new ResponseEntity<Error>(HttpStatus.CONFLICT);
}

}

  • Related