Days in a Row

A habit takes time to stick, and nothing keeps you going like a streak: the number of days in a row on which you've done every habit. Once you have a few days, you won't want to break it.

At the end of the day, you click Finish the day. If everything is done, the streak goes up by one; if not, it starts again from zero. Then all the habits are unchecked, ready for tomorrow. A real app could also do this by itself at midnight, with dates; with a button, you can try it out without waiting a day.

The streak has to survive closing the page too, so it gets the composable, under a key of its own. That's what composables are for: one line, and another value is saved.

const streak = useLocalStorage("streak", 0);

function finishDay() {
    if (allDone.value) {
        streak.value++;
    } else {
        streak.value = 0;
    }
    for (const habit of habits.value) {
        habit.done = false;
    }
}

allDone is the computed value from the progress, so in the script, it needs .value. The loop goes through all the habits and unchecks them, and the watcher in useLocalStorage saves each change.

The streak and the button go at the end of <template v-else>, under the form:

<div class="day">
    <p>Days in a row: {{ streak }}</p>
    <button @click="finishDay">Finish the day</button>
</div>

Instructions

  1. Under habits, create streak with the composable, write finishDay() from above, for now without the loop, and add the div with the class day to the template. Check all the habits off and click Finish the day: Days in a row: 1. Uncheck one and click Finish the day again: back to 0.

  2. Add the loop to the end of finishDay(). Now, when you finish the day, all the habits are unchecked, and the next day can begin.