Local storage in an Angular stand-alone component

138 Views Asked by At

I am trying to access local storage in an Angular stand-alone component.

Like this:

  Addtodo(todo: Todo) {
    console.log('I am hit here for adding Todo');

    console.log('I have been in Git in the parent', todo);

    const result = this.todos?.push(todo);
    localStorage.setItem("todos", JSON.stringify(this.todos))


    console.log('rebjhbhjewbjker', result);
  }

But I am getting an error:

[vite] Internal server error: localStorage is not defined

I am trying to access local storage.

1

There are 1 best solutions below

0
Naren Murali On

LocalStorage does not exist on the server. Please wrap the code that is failing in an if condition which checks if the platform the code is running on is from the browser!

import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

...
isBrowser: boolean;
...

constructor(@Inject(PLATFORM_ID) private platformId) {
    this.isBrowser = isPlatformBrowser(platformId);
}

Addtodo(todo: Todo) {
    console.log('I am hit here for adding Todo');

    console.log('I have been in Git in the parent', todo);

    const result = this.todos?.push(todo);
    if(this.isBrowser) {
        localStorage.setItem("todos", JSON.stringify(this.todos))
    }

    console.log('rebjhbhjewbjker', result);
}