2

In Vue.js 2, I'm using Axios and I can't render the data without refreshing the page, can you help me on what to do?

<div v-for="task in tasks" :key="task.id" class="title">
    {{ task.title }}
</div>
export default {
  name: "TodoList",
  data() {
    return {
      tasks: [],
      newTask: "",
      taskId: null,
    }
  },
  methods: {
    async addTask() {
      this.taskId = this.tasks.length + 1
      if (this.newTask.trim().length === 0) {
        return
      }
      const task = {id: this.taskId, title: this.newTask}
      const created = await API.createTasks(task)
      this.tasks.push(created)
      this.newTask = ""
    }
  },
  async created() {
    this.tasks = await API.getTasks();
  }
}
// API.js
export default {
  async createTasks(task) {
    return axios.post(this.withPath('/api/v1/tasks'),task).then(r => r.data)
  }, 
  async getTasks() {
    return axios.get(this.withPath('/api/v1/tasks')).then(r => r.data)
  },
}

This is my response body of POST:

{"id":1,"title":"buy a water"}
tony19
  • 125,647
  • 18
  • 229
  • 307
dreuma
  • 36
  • 1
  • Where we are updating value of `newTask` ? `addTask` method will always return after execution of first if block as `newTask` will always be an empty string. – Debug Diva Feb 26 '22 at 05:22
  • @RohìtJíndal in this code: `const created = await API.createTasks(task)`, i used post method to add data with task object, it have newTask variable. This is my get request method: `async createTasks(task) { return axios.post(this.url + '/api/v1/tasks',task).then(r => r.data) }` – dreuma Mar 17 '22 at 21:03
  • Can you share a link to a reproduction in StackBlitz (or Codesandbox or Codepen)? In the reproduction, instead of `/api/v1/tasks`, use jsonplaceholder (or a similar service). Creating this repro might help you better understand the cause of the problem, which could facilitate fixing the problem yourself. – tony19 Mar 17 '22 at 21:18
  • when i try this `console.log(created)` it returns nothing. – dreuma Mar 17 '22 at 21:47
  • There's not enough context to determine the problem. Please share a link to a reproduction (as mentioned above). – tony19 Mar 18 '22 at 00:14

0 Answers0