user11751578
user11751578

Reputation: 91

How to reload page after using fetch

Was wondering why my code below isnt working. Basically I am fetch data from my url to delete something. on delete, it should refresh. however it doesnt seem to let me do that. But what it does is delete the post if i manually refresh the page.

Works when I use Ajax method though which I don't know why.

Fetch method

const deleteBTN = document.querySelectorAll('.deleteBtn');
const update = document.querySelectorAll('.postedNote');

console.log(deleteBTN);

for (let btn of deleteBTN) {
    btn.addEventListener('click', (e) => {
        console.log("Delete from front end");
        console.log(btn[btn])
        let id = e.target.dataset.btn;
        fetch('http://localhost:3000/api/notes' + '/' + id, {
            method: "DELETE",
        }).then(() => {
            Location: reload()
        })
    })
}

Ajax method

$(".deleteBtn").click((e) => {
    $.ajax({
        type: "DELETE",
        url: `http://localhost:3000/api/notes/${e.target.dataset.btn}`,
        success: function () {
            console.log("delete success");
        },
    }).done(
        setTimeout(() => {
            window.location.reload();
        }, 500)
    );
});

Upvotes: 2

Views: 13101

Answers (2)

Hemant Kumar
Hemant Kumar

Reputation: 324

We can reload by using window.location.reload as already doing on ajax success.

Kindly find below as code snippet

const deleteBTN = document.querySelectorAll('.deleteBtn');
const update = document.querySelectorAll('.postedNote');

console.log(deleteBTN);



for (let btn of deleteBTN) {
    btn.addEventListener('click', (e) => {
        console.log("Delete from front end");
        console.log(btn[btn])
        let id = e.target.dataset.btn;
        fetch('http://localhost:3000/api/notes' + '/' + id, {
            method: "DELETE",
        }).then(() => {
            window.location.reload();
        })
    })
}

Also, a few considerations below The use of Ajax is defeated here as we are reloading the page. Either

  • we should perform some DOM manipulation to delete the deleted post from the page

Or,

  • in case we are using React, we can bind posts to state and then delete the deleted post on API success call, so that component is re-rendered and we do not need to refresh the page.

Upvotes: 2

Edwin
Edwin

Reputation: 37

I think you should'nt try to reload the page when removing one of the elements, instead I would have checked the response status and manually update the DOM to make the deleted element disappear if response says it was removed successfully.

Upvotes: 0

Related Questions