Fernandes
Fernandes

Reputation: 25

Auto-refresh after POST data with fetch

I try to make simple to do list with fetch method; all request works fine to see results I have to refresh website if I try to add function updateData to promise in add or deleteTask, the whole list is doubled. Could I ask for some hint on how to make it work with the auto refresh? I'm using JSON server to store data.

   function updateData() {
            var ul = document.querySelector('.listOfTasks');

            fetch('http://localhost:3000/tasks')
                .then((res) => res.json())
                .then((data) => {
                    let tasks = '';
                    data.forEach(function (task) {
                        tasks +=
                            `<li class="taskElement" id=${task.id}><input type="checkbox" class="checkbox">
                                <span class="task"> ${task.name}</span>
                                <img class="deleteBtn" id=${task.id} src="../assets/trash.png"> </img>
                             </li>`

                    })
                    ul.insertAdjacentHTML('afterBegin', tasks)
                })
        }



function addTask(e) {
        e.preventDefault();
        var taskName = document.querySelector('.taskName').value;
        var ul = document.querySelector('.listOfTasks');
        if (taskName === "") {
            alert("Please write something")
        } else {
            fetch('http://localhost:3000/tasks', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({name: taskName})
            })
                .then((res) => res.json())
        }
    }

function deleteTask(e) {
        e.preventDefault();

        if (e.target.className === 'deleteBtn') {

            fetch('http://localhost:3000/tasks/' + e.target.id, {
                method: 'DELETE',
            })
                .then((res) => res.json())
                .then((data) => console.log(data))

        }
    }

Upvotes: 0

Views: 3740

Answers (1)

ADyson
ADyson

Reputation: 62074

If you you want to run updateData() to refresh your list, then you need to replace the content of the <ul> instead of adding to it.

Therefore simply change

ul.insertAdjacentHTML('afterBegin', tasks);

to

ul.innerHTML = tasks;

See https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML for documentation.

Upvotes: 1

Related Questions