0

I made some project 3 months ago that I now need to get working again. It's a weather forecast app where you search location from google maps and save location to a my places list. Everything worked fine 3 months ago but now I get error when trying to save location and I can't figure out why:

project

 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at HomeComponent.addNewPlace (home.component.ts:65)
    at HomeComponent_Template_a_click_17_listener (home.component.html:20)
    at executeListenerWithErrorHandling (core.js:15265)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:15303)
    at HTMLAnchorElement.<anonymous> (platform-browser.js:582)
    at ZoneDelegate.invokeTask (zone-evergreen.js:406)
    at Object.onInvokeTask (core.js:28540)
    at ZoneDelegate.invokeTask (zone-evergreen.js:405)
    at Zone.runTask (zone-evergreen.js:178)

Here is HomeComponent.ts:

 

    import { Component, OnInit } from '@angular/core';
    import { MapsAPILoader } from '@agm/core';
    import { NgZone, ViewChild } from '@angular/core';
    import { ElementRef } from '@angular/core';
    import { Place } from '../models/place/place.module';
    import { LocationService } from '../location.service';
    import { LocalStorageService } from '../local-storage.service';
    import { Subscription } from 'rxjs';

    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.css']
    })
    export class HomeComponent {
      title = 'weather-forecast-app';
      latitude: number;
      longitude: number;
      zoom: number;
      address: string;
      private geoCoder;
      location = this.locationService.getLocation();

      placeList: Place[]=(JSON.parse(localStorage["storedData"] || '[]'));
      

      @ViewChild('search')

      public searchElementRef: ElementRef;

      constructor(
        private mapsAPILoader: MapsAPILoader,
        private ngZone: NgZone,
        private locationService: LocationService,
        private localStorageAs: LocalStorageService,
        
      ) { }

      ngOnInit() {
      
        this.mapsAPILoader.load().then(() => {
          this.setCurrentLocation();
          this.geoCoder = new google.maps.Geocoder;

          let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
          autocomplete.addListener("place_changed", () => {
            this.ngZone.run(() => {
              let place: google.maps.places.PlaceResult = autocomplete.getPlace();

              if (place.geometry === undefined || place.geometry === null) {
                return;
              }

              this.latitude = place.geometry.location.lat();
              this.longitude = place.geometry.location.lng();
              this.zoom = 12;
              this.getAddress(this.latitude, this.longitude);
            });
          });
        });
        
      }

      addNewPlace(lat,long,address){
        this.placeList=(JSON.parse(localStorage["storedData"]));
        this.placeList.push(
          new Place(parseFloat(lat),parseFloat(long),address)
        );
        alert(address+" added to your locations");  

     this.localStorageAs.set("storedData",JSON.stringify(this.placeList));

      }

      private setCurrentLocation() {
        if ('geolocation' in navigator) {
          navigator.geolocation.getCurrentPosition((position) => {
            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude;
            this.zoom = 12;
            this.getAddress(this.latitude, this.longitude);
           
          });

        }

      }
      getAddress(latitude, longitude) {

        this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, status) => {
          if (status === 'OK') {
            if (results[0]) {
              this.zoom = 12;
              this.address = results[0].address_components[results[0].address_components.length-4].long_name;
              this.locationService.setLocation({latitude, longitude, address: results[0].address_components[results[0].address_components.length-4].long_name});
            } else {
              window.alert('No results found');
            }
          } else {
            window.alert('Geocoder failed due to: ' + status);
          } 

        });
      } 



    }

I made it whit teammate who I'm not in contact anymore so I can't ask him and I'm not sure about everything that's done here.

Henri
  • 15
  • 2
  • Does this answer your question? [Uncaught SyntaxError: Unexpected token u in JSON at position 0](https://stackoverflow.com/questions/46613243/uncaught-syntaxerror-unexpected-token-u-in-json-at-position-0) – R. Richards Sep 11 '21 at 11:11

2 Answers2

0

It seems that you don't have any placeList stored in your localStorage, so the JSON.parse throwing this error.

You just need to check the localStorage if it has a value with the provided key storedData or not before passing it to the parser.

You can try the following:

addNewPlace(lat, long, address) {
    const placeListJson = localStorage['storedData'];
    this.placeList = placeListJson ? JSON.parse(placeListJson) : [];

    this.placeList.push(new Place(parseFloat(lat), parseFloat(long), address));
    alert(address + ' added to your locations');

    this.localStorageAs.set('storedData', JSON.stringify(this.placeList));
}
Amer
  • 6,162
  • 2
  • 8
  • 34
  • 1
    Wow it works perfectly. Thank you for your time! As storage services are made by my teammate I don't get it why it worked before and now threw error. – Henri Sep 11 '21 at 11:02
0
addNewPlace(lat, long, address) {
    this.placeList = JSON.parse(localStorage.getItem('storedData')) || [];
    const newPlace = new Place(parseFloat(lat), parseFloat(long), address);
    this.localStorageAs.set('storedData', JSON.stringify([...this.placeList, newPlace]));
    alert(address + ' added to your locations');
}
navnath
  • 3,548
  • 1
  • 11
  • 19