DEV Community

Cover image for Day 19: Add Habits function
Margaret W.N
Margaret W.N

Posted on

Day 19: Add Habits function

After my one day vacation I am back to work. Took on the initially frustrating add habits function. This is how worked around it.

I wrapped the inputs in a form with an Id of form. In the index.js file I'll get this form element and chain an event listener. I'll pass in a submit event and a function as parameters. The function takes event as a parameter and perform the following operations

  • Prevents default action of submit event.
  • Gets the value of my inputs and saves them to a variable I tried using different variable names other than the database properties and the data wasn't being saved. I don't know why but atleast i know it doesn't work.
  • Passes the captured variables as properties of an object(habit)
  • Sends a post request with a URL and the the object
  • And Lastly reloads the page.
const form = document.getElementById('form');

form.addEventListener('submit', async (event) => {
    event.preventDefault();

    const title = document.getElementById('habit').value;
    const description = document.getElementById('description').value;

    const habit = { title, description }

    const response = await axios.post('http://localhost:4000/habittracker/habits', habit)

    location.reload()
  })
Enter fullscreen mode Exit fullscreen mode

The results.

A shout out to @nathanbarrett for the pointers.

That's it for Day 19!

Top comments (0)