Day 19: Add Habits function

mtee

Margaret W.N

Posted on August 4, 2020

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!

πŸ’– πŸ’ͺ πŸ™… 🚩
mtee
Margaret W.N

Posted on August 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Day 23 of 100DaysOfCode
javascript Day 23 of 100DaysOfCode

October 3, 2024

Day21 of 100DaysOfCode
javascript Day21 of 100DaysOfCode

August 22, 2024

Day22 of 100DaysOfCode
javascript Day22 of 100DaysOfCode

September 7, 2024

Day 2 of #100daysofMiva Coding Challenge
100daysofmiva Day 2 of #100daysofMiva Coding Challenge

August 22, 2024