为什么删除按钮会删除所有项目而不是单个项目?

huangapple go评论57阅读模式
英文:

Why the delete button is deleting all af the items instead a single one?

问题

After creating a new to-do item in the list, after clicking the delete button all of the new tasks are deleted instead of the single one. I'm expecting only the appropriate one with a passed id to be deleted.

英文:

After creating a new to do item in the list, after clicking the delete button all of the new tasks are deleted insetead the single one. I'm expecting to be deleted only the propriete one with a passed id with it.

https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=pages%2Findex.vue,store%2Findex.js,components%2FTask.vue

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// Child component

&lt;template&gt;
    &lt;p class=&quot;content&quot;&gt;
      {{ task.todo }}
    &lt;/p&gt;
    &lt;button @click=&quot;() =&gt; deleteTask(task.userId)&quot; class=&quot;delete&quot;&gt;
      Delete
    &lt;/button&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  props: [&#39;task&#39;],
  methods: {
    deleteTask(id) {
      this.$store.dispatch(&#39;deleteTask&#39;, id);
    },
  },
};
&lt;/script&gt;

// Parent component

&lt;template&gt;
  &lt;Task v-for=&quot;task in tasks&quot; :key=&quot;task.id&quot; :task=&quot;task&quot; /&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  computed: {
    tasks() {
      return this.$store.state.tasks;
    },
  },
  mounted() {
    this.$store.dispatch(&#39;getTasks&#39;).then((data) =&gt; console.log(this.tasks));
  }
};
&lt;/script&gt;

// Store

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

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

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

<!-- end snippet -->

答案1

得分: 0

Sure, here's the translation of the provided text:

"请纠正我如果我错了,但是不应该是传递要删除的任务的 任务ID 而不是 用户ID 吗?

比较:

在这里对我有效:

我按照上面提到的做法,将 task.id 添加了,而不是 user.id,然后我删除了 res.ok,只保留了 res

然后添加了 .then 并删除了标头。我不认为这很重要,但我查看了文档,示例没有使用它。

现在,你唯一需要做的是更新列表,可能添加一些错误处理,如果出现问题的话。

更新:

修复列表没有渲染的问题是因为你需要更新存储中的任务状态。当前 deleteTask 操作正在分派 getTasks,它从服务器获取任务并更新存储。

但它是异步的,因此在组件重新渲染之前可能无法更新状态。这就是为什么控制台日志中的列表是“正确的”,但在实际DOM树中看到的不是这样的原因。

现在,这将立即更新存储中任务的状态,并且组件将使用更新后的列表重新渲染。

我选择使用 res.ok 并尝试保持它与你的代码一开始的样子。"

英文:

Correct me if I'm wrong but shouldn't be that you are passing in the task ID of the task you want to delete and not the user ID?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;button @click=&quot;() =&gt; deleteTask(task.id)&quot; class=&quot;delete&quot;&gt;
  Delete
&lt;/button&gt;

<!-- end snippet -->

Compare to :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    &lt;button @click=&quot;() =&gt; deleteTask(task.userId)&quot; class=&quot;delete&quot;&gt;
      Delete
    &lt;/button&gt;

<!-- end snippet -->

Update :

There it work for me :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 async deleteTask(context, id) {
    const res = await fetch(`https://dummyjson.com/todos/${id}`, {
      method: &#39;DELETE&#39;,
    })
      .then((res) =&gt; res.json())
      .then(console.log);
    if (res) {
      let result = await res.json();
      context.dispatch(&#39;getTasks&#39;);
    }
    return res;
  }

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

completed: true
deletedOn: &quot;2023-05-06T14:01:35.302Z&quot;
id: 103
isDeleted: true
todo: &quot;Go to a local thrift shop&quot;
userId: 5

<!-- end snippet -->

I did as I mention above and added the task.id instead of user.id and then I removed the res.ok just to res.

Then added .then and removed the headers. I don't think it matters but I looked at the docs and the example didn't use it so.

The only thing left for you is to update the list and maybe add some error handling if something doesn't goes as planned.

Update :

To fix that the list isnt render is because you need ot update the state of tasks in the store. Right now the deleteTask action is dispatching the getTasks which fetches the tasks from the server and updates the store.

But its asynchronous, so the state may not be updated before the component is rerendered. That's why the list is "right" in the console logs but not as you see it in the actual DOM tree.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

async deleteTask(context, id) {
  const res = await fetch(`https://dummyjson.com/todos/${id}`, {
    method: &#39;DELETE&#39;,
  });
  if (res.ok) {
    // filter the tasks in the state to remove the deleted task
    const tasks = context.state.tasks.filter(task =&gt; task.id !== id);
    context.commit(&#39;setTasks&#39;, tasks);
  }
  return res.ok;
}

<!-- end snippet -->

Now this will update the state of the tasks in the store immediately and the component will rerender with the updated list.

I went with the res.ok and tried to keep it as your code looked from the start.

答案2

得分: 0

问题不在于 DELETE 功能!
当我查看代码和API响应时,问题不在于删除功能。
问题出在 todos/add API 上,通过该API创建新任务。
我可以看到包含 completed: false 的JSON响应,表明任务尚未创建。

那为什么它在创建时显示为新任务,为什么删除特定任务后所有新任务都消失了?

  1. 创建新任务时,当API响应为 OK 时,您将任务追加到任务列表中。(当然,即使任务未被存储,API也会以OK状态响应)
  2. 在删除特定任务后,您会从服务器重新获取任务列表(它只会给出那些已被存储的任务。如我之前提到的,没有任务被保存,因此它似乎 删除了所有任务而不是一个

现在该怎么办?
最好去后端查看您编写存储任务代码的地方,检查为什么它没有被存储。

注意:在创建任务后,您查看状态为 OK 时,最好也查看包含 completed: true 的响应。

英文:

The issue is not with the DELETE functionality!!
When I looked the code and the API responses, the issue is not with the delete functionality.
The issue is with the todos/add API through which you create a new task.
I could see the response with json including the completed: false, indicating that the task has not been created.

Then why is it showing as a new task when created and why all new tasks are vanishing on deleting a particular task ?

  1. While creating a new task, you are appending the task to your tasks list when the API response is OK. (of course, the API is responding with OK status though the task is not being stored )
  2. Once after deleting of a particular task, You are re-fetching the task list from the server ( and it'll give only those tasks which are being stored. And as I mentioned earlier, no task is being saved so it appears that it deleted all the tasks instead of one

What to do now ?
You better go, look at the backend where you wrote the code to store the tasks and check why it's not being stored.

NOTE : Once after creating the tasks, you are looking at the status to be OK, you better also look for the response with containing completed : true

huangapple
  • 本文由 发表于 2023年5月6日 21:08:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定