Home > OS >  Send request depending on a condition from a previous request
Send request depending on a condition from a previous request

Time:05-26

I want to send request depending on a condition from a previous request.

This is my code:

const sendFriendRequest_ver_2 = (requestFrom, requestTo, requestFromUserType = "INDIVIDUAL_USER", requestToUserType = "INDIVIDUAL_USER") => {

const data = {
    requestFrom,
    requestTo,
    requestFromUserType,
    requestToUserType,
}
api.get(`/api/friendship-request?userId=${requestTo}&userType=INDIVIDUAL_USER`)
    .then(res => {
        const found = res.data.some(item => item.id === requestFrom);
        if (found) {
            console.log('invite already sent')
        } else {
            console.log('sending now')
            api.post('/api/friendship-request', data).then(res => {
            }).catch(e => console.log(e))

        }
    })
    .catch(e => console.log(e))
}

It works but I am new to programing and I am not sure if this is the 'best' way to do this.

I mean I dont't know if this is good way to handle this at all.

Thanks in advance and have a nice day!

CodePudding user response:

The code you have written makes sense and you don't need to worry much about it. If you are familiar with async await syntax you should change it to that. its just more readable. Here is a layout:

const sendFriendRequest_ver_2 = (requestFrom, requestTo, requestFromUserType = "INDIVIDUAL_USER", requestToUserType = "INDIVIDUAL_USER") => {

const data = {
requestFrom,
requestTo,
requestFromUserType,
requestToUserType,
}
(async()=>{
try{
  const res = await api.get(`/api/friendship-request?userId=${requestTo}userType=INDIVIDUAL_USER`)
  const found = res.data.some(item => item.id === requestFrom);
  if (found) {
        console.log('invite already sent')
    } else {
        console.log('sending now')
      const res =  api.post('/api/friendship-request', data)

    }
 }
 catch(error){
      console.log(e)
 }
 })()
  • Related