Search code examples
if-statementfetchhttprequestput

Can I use a conditional with fetch for both a put and delete request?


My code editor is saying something is wrong... Is it due to me writing it poorly or is an if-statement with different requests just not possible?

changeLikeCardStatus(cardId, like) {
    return fetch(`${this._baseUrl}/cards/likes/${cardId}`, {
      if(like){
        method: "PUT",
        headers: this._headers
      } else {
        method: "DELETE",
        headers: this._headers
      } 
    }).then((res) =>
      res.ok
        ? res.json()
        : Promise.reject(`Error! ${res.statusText}`).catch((err) =>
            console.log(err)
          )
    );
  }``` 

Solution

  • Instead of using conditions inside fetch, apply condition before the return statement, and find the needed method and use that method in fetch. In the below code I have added a statement to get the method name using ternary condition. Please modify it according to the language, and try if it is working

    changeLikeCardStatus(cardId, like) {
    methodName = like?"PUT":"DELETE";
        return fetch(`${this._baseUrl}/cards/likes/${cardId}`, {
          
            method: methodName,
            headers: this._headers
         
        }).then((res) =>
          res.ok
            ? res.json()
            : Promise.reject(`Error! ${res.statusText}`).catch((err) =>
                console.log(err)
              )
        );
      }