What is the best way to remove a task from your task list?

I am encountering a 404 error while trying to delete an individual task from the array using a DELETE request. The URL is correct and I am passing the userId in the method, but should I be using id instead? It's worth noting that the URL array contains both the userId and the id for each element.

Link to StackBlitz

// Child component

<template>
  <div :class="{ task: task.completed }">
    {{ task.todo }}
    <button @click="deleteTask" class="delete">Delete</button>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: ['task'],
    deleteTask(userId) {
      this.$store.dispatch('deleteTask');
    },
  },
};
</script>

// Parent component

<template>
  <Task v-for="task in tasks" :key="task.id" :task="task" />
</template>

<script>
export default {
  data() {
    return {
      todo: '',
      completed: false,

    };
  },
  computed: {
    tasks() {
      return this.$store.state.tasks;
    },
  },
  created() {
    this.$store.dispatch('getTasks').then((data) => console.log(this.tasks));
  },
  methods: {
  },
};
</script>

// Store 

export const state = () => ({
  tasks: [],
});

export const actions = {
  async getTasks(context) {
    const res = await fetch('https://dummyjson.com/todos');
    if (res.ok) {
      let result = await res.json();
      context.commit('setTasks', result.todos);
    }
    return res.ok;
  },
  async deleteTask(context, id) {
    const res = await fetch(`https://dummyjson.com/todos/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
      },
    });
    if (res.ok) {
      let result = await res.json();
      context.dispatch('getTasks');
    }
    return res.ok;
  }
};

export const mutations = {
  setTasks(state, data) {
    state.tasks = data;
  }
};

Answer №1

Make sure to include the id

@click="deleteTask(task.id)"
within your HTML code, and in the corresponding method:

deleteTask(id) {
  this.$store.dispatch('deleteTask', id);
},

Answer №2

You are encountering a 404 error because you are trying to access

https://dummyjson.com/todos/undefined

1 - To resolve this issue, make sure to pass the correct id:

// Check Task.vue - line 26
deleteTask(id) {
      this.$store.dispatch('deleteTask', id);
},

2 - Additionally, remember to invoke the "deleteTask" method with the right id:

// Check Task.vue - line 10
<button @click="() => deleteTask(task.id)" class="delete">Delete</button>

Once these steps are completed, you should be able to call https://dummyjson.com/todos/1

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resolve problem with npm peerDependencies for specific package

One issue my application is facing involves a set of domain packages that all have the core as a peer dependency. The structure of these domain packages is as follows: "name": "domain-a-pckg", "peerDependencies":{ "core-p ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Angular9: construction involves an additional compilation process

After updating my Angular8 project to Angular9, I noticed a new step in the build process which involves compiling to esm. This additional step has added approximately 1 minute to my build time. A snippet of what this step looks like: Compiling @angular/ ...

Is it possible for me to access information from an external URL using JSON?

As I delve into learning about JSON for app development, I've encountered an issue with a JSON and PHP-based chat system. While the code functions properly for the same origin policy, when it comes to sending and receiving data from an external URL, i ...

Currently, I am a beginner in the world of reactjs and I have embarked on a practice project to expand my knowledge of the platform. I am in need of assistance in creating a feature that

fetch("https://sampleapi.com/api/v1/employees").then( response => { response.json().then( result => { console.log(result.data); if (result.data.length > 0) { var content = ""; re ...

I attempted to establish a connection between my backend and the MongoDB database, however, an error was displayed

Error: Failed to establish a connection to the database! MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 Please check the database connection settings and try again. For more information, refer to the error log. ...

Is there a way to link dynamic server fields with VueJS?

How can I bind data posted by the server with Vue.js in order to display the data instead of field names? <script> module.exports = { data: function () { return { filedNameFromServer: ['{{filed1}}' ...

What is causing VSCode's TypeScript checker to overlook these specific imported types?

Encountering a frustrating dilemma within VS Code while working on my Vite/Vue frontend project. It appears that certain types imported from my Node backend are unable to be located. Within my frontend: https://i.stack.imgur.com/NSTRM.png The presence o ...

Ways to consistently stream information from server to browser

I have a file that is constantly being updated with the following contents: id,value,location 1234,pass,/temp/... 234,fail,/temp/r/... 2343,pass,/temp/status/... The file keeps updating for approximately 1 hour by a program. I want to display ...

Implementing color to text in React JS

Is it possible to change the color of text using inline styles within the HTML tag itself? If so, how can I achieve this? <div id="root"></div><br> <script src="https://unpkg.com/react@16/umd/react.development.js"></script>& ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

Implementing setTimeout with the copy button: A guide

How can I implement a setTimeout function in the copy button so that when a user clicks on it, the text will change to "copied" and then revert back to "copy" after 3-4 seconds? Please help me find a solution to this problem and also optimize the JavaScrip ...

Interactive Animation featuring Interactive Pop-up Boxes

I am facing an issue with the 'zoomIn' animation where the background: rgba(0, 0, 0, 0.5); is not present when the popup box appears. I want the background to be there from the start of the animation. Additionally, after clicking the Submit butt ...

Numerous datasets of bubble charts available for use in chartjs

I have an array named main_arr that contains multiple data arrays. To visually represent these different arrays, I am utilizing a bubble chart where each one is displayed in a distinct color. var myBubbleChart = new Chart(ctx, { type : 'bubble&a ...

PhantomJS 2.0.0 not delaying page loading

In the script provided, there is an array of URLs called links. The function gatherLinks() is designed to collect additional URLs from the sitemap.xml file related to the ones in the links array. Once the number of URLs in the links array reaches a certain ...

What are the steps to incorporate metrics middleware for Socket IO notifications, specifically monitoring both emitted events and listener activity?

I am currently working on a project that involves tracking all socket.io notification transactions initiated by the server, resembling an API request/response counter to validate subscription validation. Our team is utilizing an express middleware to moni ...

Encountering the error message "Cannot GET /" in a NodeJS Express

I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...

The data I am trying to obtain is not being returned by my hook as expected

I am trying to create a hook that fetches all properties from a database. The function I have is asynchronous, and when I call the hook in another function, it returns an empty array []. I understand that fetching data from the database is an asynchronous ...

Ways to increase the field count in PHP seamlessly with the help of JavaScript, jQuery, or AJAX, without the need to

Within my Yii form, there is a text field labeled certificate_name. I am looking to create a functionality where clicking on the plus icon will increment the text field by one and display it below the previous field. Below is the PHP code snippet I am usi ...