After successfully deleting an item from an api, the list of items updates only after the second click on the same item. Using fetch, vue 3 composition API and django rest api. Created an async function for both getting data from an api and deleting data from it. How can you update/ make a get request for the objects once one of the items in the list is deleted?
<template>
<div id="restTodo">
<div class="TodoContainer">
<div v-for="todo in todos" v-bind:key="todo.id" class="TodoComponent">
<div class="TodoValue">{{ todo.todo }}</div>
<div class="TodoValue">{{ todo.completion }}</div>
<button class="TodoValue" id="buttonComplete">+</button>
<button
class="TodoValue"
id="buttonDelete"
@click="removeTodo(todo.id)"
>
X
</button>
</div>
</div>
</div>
</template>
<script>
import { ref, onMounted } from "vue";
export default {
setup() {
const todos = ref([]);
const API_URL = "http://127.0.0.1:8000/api/todo-list/";
const API_DELETE = "http://127.0.0.1:8000/api/todo-delete";
async function getTodos() {
const response = await fetch(API_URL);
const json = await response.json();
todos.value = json;
}
// // // // // // // // // // // //
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== "") {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === name + "=") {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie("csrftoken");
// // // // // // // // // // // //
async function removeTodo(id) {
var csrftoken = getCookie("csrftoken");
fetch(`${API_DELETE}/${id}/`, {
method: "DELETE",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
})
// .then(console.log(`deleted item ${id}`))
.then(getTodos())
}
// // // // // // // // // // // //
onMounted(() => {
getTodos();
});
// // // // // // // // // // // //
return {
todos,
removeTodo,
csrftoken,
};
},
};
</script>
Ok, changing the removeTodo function .then updates things.
async function removeTodo(id) {
var csrftoken = getCookie("csrftoken");
fetch(`${API_DELETE}/${id}/`, {
method: "DELETE",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
}).then((response) => {
getTodos()
return response
})
}