Search code examples
javascriptfetchstring-comparison

Why is my string comparison in fetch response not working properly?


Basically, I am posting id of draft to server to delete draft using fetch and server will response with success text if it succeeds. Here is my code.

fetch(this.url + "/vue/api/processdraft?action=delete&id=" + item.id, {
    method: "POST"
})
    .then(response => {
        return response.text();
    })
    .then(function (response) {
        console.log(response);
        if (response === "success") {
            console.log("Test");
            this.draftList.splice(index, 1);
        }
    });

In above code, in console.log(response) shows success as expected. But code inside if block doesn't work. And I cannot figure out what is wrong with it? It won't even print Test as it is supposed to. Here is screenshot of output.

enter image description here

And I've also checked that there is no white space before or after response text if it matters.

Edit: I checked for whitespaces in serverside and although I made sure there were no whitespace, but forgot to consider newline character. So this've been solved using trim() as suggested by answers.


Solution

  • You can try to use tim():

    .then(function (response) {
        console.log(response);
        if (response.trim() === "success") {
            console.log("Test");
            this.draftList.splice(index, 1);
        }
    });
    

    Hope it'll work.