skip to Main Content

I’m expecting to add a new task object and visualize it in the parent component array by clicking the Add button. But I’m havingg an error newTask is not defined. Even though I’m forming the newTasks in the child component and passing it to the parent array in the vuex.

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

// Child component

methods: {
    addTask() {
      let newTask = {
        id: Math.floor(Math.random() * 25),
        title: this.title,
        completed: false,
      };
      if (newTask) {
        console.log(newTask);
        this.$store.dispatch('addTask', newTask);

        this.title = '';
      }
    },
  }
  
  // Store
  
  export const state = () => ({
  tasks: [],
});
  
  const actions: {
    async addTask(context, data) {
    data = {
      ...data,
      newTask,                        // getting an error here - newTask is not defined
 
    };
    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.dispatch('getTasks');
    }
    return res.ok;
  },
  }
  
  const mutations: {
    setTasks(state, data) {
    state.tasks = data;
    },
  }

store

3

Answers


  1. It looks like you’re trying to pass newTask as a property of the data object that’s being sent in the addTask action, but newTask is not defined in the scope of the actions object.

    To fix this issue, you can simply remove the newTask property from the data object:

    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.dispatch('getTasks');
        }
        return res.ok;
    },
    

    You’re already passing the newTask object as the second argument to the addTask action in the child component (this.$store.dispatch('addTask', newTask)), so it will be available as the data parameter in the action.

    Additionally, in the setTasks mutation, you’re setting the state.tasks to the entire response data object (state.tasks = data), but you probably only want to set it to the newly added task object. To fix this, you can change the mutation to:

    mutations: {
        setTasks(state, newTask) {
          state.tasks.push(newTask);
        },
    }
    

    This will add the new task to the state.tasks array instead of overwriting it with the entire response data object.

    Login or Signup to reply.
  2. I checked your project and I found the error.

    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.dispatch('getTasks');
        }
        return res.ok;
    },
    

    When you call API, Backend doesn’t add newTask, This is error.
    So when you get response, there isn’t newTask data that you added.

    Login or Signup to reply.
  3. Do you have got back-end code?
    I think you should modify the controller about https://jsonplaceholder.typicode.com/todos request.
    In this controller, the addTask request isn’t processed.
    The addTask request doesn’t insert to DB.
    You have to modify the controller of back-end.
    And you can give me the back-end, then I will solve this error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search