Search code examples
javascriptvue.jsvuexvue-propsonvif

How to visualize the tasks array title in the component?


I'm expecting to get visualized title of the task in the child component after creating the new task via Add button. The completed button is rendered in the dom, but the title isn't now. https://stackblitz.com/edit/nuxt-bootstrap-vue-dynamic-img-bkwixg?file=pages%2Findex.vue,components%2FTask.vue,store%2Findex.js

// Task child component 

<template>
  <div :class="{ task: task.completed }">
    <p class="content">
      {{ task.title }}
    </p>
    <div class="buttons">
      <button @click="toggleTask">
        {{ task.completed ? 'Undone' : 'Done' }}
      </button>
      <button @click="deleteTask" class="delete">Delete</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: ['task'],
</script>

// Parent component

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

// Store

export const state = () => ({
  tasks: [title= "", completed= false,...],
});


Solution

  • This is because you are relying on what the API responds with. Usually this is the more reliable way of dealing with it so that the API and client are nsync. However, this mock api only responds with the following response

    {id: 201}
    

    So you're going to have an issue with IDs and will be missing the other parameters. If you're going to use this mock API, you can use your own data instead of the response. Here is the addTest action

      async addTask(context, data) {
        const res = await fetch('https://jsonplaceholder.typicode.com/todos', {
          method: 'POST',
          headers: {
            'Content-Type': 'appication/json;charset=utf-8',
          },
          body: JSON.stringify(data),
        });
        if (res.ok) {
          let result = await res.json();
          context.commit('addnewTask', result); // 🔴 uses response
          context.commit('addnewTask', data); // 🟢 uses the data
    
        }
        return res.ok;
      },