Tips for preventing LocalStorage data from being overwritten in Angular

I have been working on a scheduler to track tasks completed within a specific timeframe.

Whenever I click "STOP," an input field appears where I can enter details about the task I just finished. The start time, end time, and duration of the task are then saved accordingly.

Currently, the main function I am focusing on fixing is "addTask()." I am attempting to store these tasks using LocalStorage, but each new entry overwrites the previous one instead of creating a list.

Below is the full code implementation:

HTML:

<div class="modalbox" [class.active]="modalboxActive">
  <div class="modal">
    <p>What task did you complete?</p>

    <input type="text" [(ngModel)]="activity.name" />
    <button (click)="addTask()" [disabled]="activity.name === ''">OK</button>
  </div>
</div>
<div class="boxSuper">
  <div class="boxLeft">
    <div class="containerUp">
      <button id="start" (click)="startTimer()">START</button>
      <button id="pause" (click)="pauseTimer()">PAUSE</button>
      <button id="stop" (click)="stopTimer()">STOP</button>
    </div>
    <div class="containerDown">
      <p>{{ display }}</p>
    </div>
  </div>
  <div class="boxRight">
    <div class="containerLeft">
      <ul class="listElementLeft" *ngFor="let item of tasks">
        <li>
          <span id="writings">Start Time:</span>
          <span>{{ item.start }}</span>
        </li>
        <li>
          <span id="writings">End Time:</span>
          <span>{{ item.end }}</span>
        </li>
        <li>
          <span id="writings">Duration:</span>
          <span>{{ item.length }}</span>
        </li>
      </ul>
    </div>

    <div class="containerRight">
      <ul class="listElement" *ngFor="let item of tasks">
        <li>
          <span id="writings">Task:</span>
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
  </div>
</div>

TS:

import { importExpr } from '@angular/compiler/src/output/output_ast';
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
import { Activity } from '../activity';
import { Result } from '../result';

@Component({
  selector: 'app-timer',
  templateUrl: './timer.component.html',
  styleUrls: ['./timer.component.css'],
})
export class TimerComponent implements OnInit {
  ngOnInit() {}
  time: number = 0;
  display: string | undefined;
  interval: any;
  modalboxActive = false;
  startTime: string | undefined;
  endTime: string | undefined;

  activity: Activity = {
    name: '',
  };

  tasks: Result[] = [];

  startFunc() {
    this.startTime = new Date().toString().split(' ')[4];
  }

  endFunc() {
    this.endTime = new Date().toString().split(' ')[4];
  }

  addTask() {
    var el: Result = {
      name: this.activity.name,
      end: this.endTime,
      start: this.startTime,
      length: this.display,
    };
    localStorage.setItem('taskList', JSON.stringify(el));
    window.localStorage.getItem('taskList');
    this.tasks.push(el);
    this.activity.name = '';
    this.modalboxActive = false;
    this.resetTimer();
  }

  resetTimer() {
    console.log('resetting timer...');
    this.time = 0;
  }

  startTimer() {
    console.log('starting timer...');
    this.interval = setInterval(() => {
      if (this.time === 0) {
        this.time++;
      } else {
        this.time++;
      }
      this.display = this.transform(this.time);
    }, 1000);
    this.startFunc();
  }

  transform(value: number): string {
    var sec_num = value;
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - hours * 3600) / 60);
    var seconds = sec_num - hours * 3600 - minutes * 60;
    return hours + ':' + minutes + ':' + seconds;
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

  stopTimer() {
    console.log('stopping timer...');
    this.modalboxActive = true;
    clearInterval(this.interval);
    this.endFunc();
  }
}

Answer №1

Local storage functions by storing a singular object in a designated location and linking it to a key, such as 'token'. This means that it will consistently replace any existing data.

If you're looking to achieve a different outcome, you could consider implementing the following approach:

var itemList = window.localStorage.getItem('token');
itemList.push(newTask)
localStorage.setItem('token', itemList);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to retrieve a single data point from [object][object]

Presented here is an angular component: import { Component, OnInit } from '@angular/core'; import { Hall } from 'src/app/models/hall.model'; import { HallService } from 'src/app/services/hall.service'; import { ActivatedRoute, ...

What is the best way to avoid special characters in Angular Date pipe?

I have a query that might have been addressed on SO before. However, none of the solutions provided so far have helped me. Therefore, I am posting this question in hopes of finding an answer: I am trying to format a string and escape the h letter within i ...

I require clarity on this befuddling syntax that feels like descending into

I came across this example in the official documentation at https://angular.io/guide/form-validation#custom-validators return (control: AbstractControl): {[key: string]: any} => { const forbidden = nameRe.test(control.value); return forbidden ...

Is there a method to prevent explicitly passing the context of "this"?

Currently, I am in the process of developing a new product and have set up both back-end and front-end projects. For the front-end, I opted to use Angular framework with Typescript. As a newcomer to this language (just a few days old), I have encountered a ...

Angular Error: Unable to access properties of null (specifically 'validators')

I am encountering an issue with my Angular code where I receive the error message "TypeError: Cannot read properties of null (reading '_rawValidators')". import { Component, OnInit } from '@angular/core'; import { Wifi } from './wi ...

Packaging an NPM module to enable unique import paths for Vite and Typescript integration

Is there a way to package my NPM module so that I can use different import paths for various components within the package? I have looked into webpack solutions, but I am working with Vite and TypeScript. This is the structure of my package: - src - ato ...

Instructions on setting a photo as a background image using a text-based model

I'm a beginner with Angular so I may have a simple question. I am using an image from the Google API, which is not a URL. How can I set this image as the background-image in a CSS tag that only accepts URIs? Thank you! ...

SSR in Angular causing a glitch where inner child pages don't load their HTML content

I'm encountering a strange issue with the loading of my angular application. Whenever I view the application online, regardless of the route I navigate to, the HTML structure always defaults back to the base path. Let's say I have 2 pages define ...

Adding properties to request object on-the-fly - Google Pay [Typescript]

Here is how I am constructing the payment request object: paymentRequestObject: google.payments.api.PaymentDataRequest = { apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [ { type: 'CARD', parameters: { allowedAuthMethod ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

"Implementing a Node.js/Express backend paired with an Angular front-end within a unified Azure web application

Currently, I have set up a Node/Express configuration for my development environment that provides JSON data through the endpoint localhost:3000/data. In addition to this, there is an Angular 8 application within the same node directory for the frontend. ...

Utilizing material-ui with Autocomplete featuring various value and option types

In my code, I am looking to store only an option's ID in a value For autocomplete functionality, the value's type and the option's type need to be the same My solution was to change the value in onChange, which worked successfully However ...

I'm puzzled as to why I am unable to invoke a class method within this callback function. The error message indicates a TypeError: 'this' is undefined

Currently, I am troubleshooting a challenge in my Angular application that involve TypeScript. The issue lies within a method in a TypeScript class: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsApplied ...

Deleting data from Firebase in Angular can be easily done using the AngularFire library. By

I am attempting to remove specific values from my Firebase database. I need to delete this entry from Firebase: https://i.stack.imgur.com/CAUHX.png So far, I have tried using a button to trigger the delete function like this: <div class="single-bfunc ...

Challenges with deploying Angular applications and dealing with undefined properties within Angular code

Currently, I have successfully added new products to the database with all the desired properties. However, I am facing errors that are preventing me from deploying the application for production. Fixing these errors causes further issues where I cannot ad ...

Struggling with the testing of @Output functionality through Jasmine

I've encountered an issue while trying to test an @Output parameter in my Jasmine test for Angular 5. It seems that the button click isn't being registered, resulting in the event emitter not triggering. Here is a snippet of my component code: ...

What is the best way to change a Date stored in an array to a string format? [angular4]

Presented here is an array with the data labeled dateInterview:Date: public notes: Array<{ idAgreement: string, note: string, dateInterview: Date }> = []; My goal is to send this array to the server where all values of dateInterview need to be co ...

Experience the enhanced Angular Material 10 Date Range Picker featuring the exclusive matDatepickerFilter functionality

Is it possible to use Angular Material 10 MatDateRangeInput with matDatepickerFilter? When attempting the following: <mat-form-field appearance="outline"> <mat-label>Label</mat-label> <mat-date-range-input [formGroup]=&q ...

ReactJS Tutorial: Simple Guide to Updating Array State Data

const [rowData, setRowData] = useState([]); const old = {id: 'stud1', name: 'jake', room: '2'}; const newData = {name: 'jake', room: '3A'}; useEffect(() => { let ignore = false; ...

Tips for incorporating recursive HTTP requests into an Angular2 service to efficiently retrieve data in advance

In my Angular project, I am using a service to fetch data from an external API. However, the API has a limit of 100 records per request and I can only determine the total number of records available after fetching the first batch. The response structure o ...