Variable from API not getting passed into local storage in Angular

Viewed 441

I am working on a reservation system where the user passes flight data - dates, cities, number of passengers. And based on the choices, the cheapest route price is calculated via Skyscanner API. Afterwards, all of the variables with assigned values are passed into localStorage. But this does not apply to the price value even though the API works fine and shows the value when checked in console.log. I tried binding it to another variable and passing the second one to local storage but also with no success.

Thanks in advance for helping solve this mystery as I'm out of ideas and double checks :)

STACKBLITZ: https://stackblitz.com/edit/local-storage-data

COMPONENT.ts

  public numberOfPassengers: number = 1;
  public departureDate: any;
  public returnDate: any;
  public departureAirport: string;
  public destinationAirport: string;
  public showStorage: any;
  public departureAPI;
  public arrivalAPI;
  public basePrice: number; //should but does not get into localstorage

getConnection() {
    fetch(
      `https://cors-anywhere.herokuapp.com/https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsequotes/v1.0/PL/PLN/en-US/${this.departureAPI}/${this.arrivalAPI}/${this.departureDate}?inboundpartialdate=${this.returnDate}`,
      {
        method: "GET",
        headers: {
          "x-rapidapi-host":
            "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com",
          "x-rapidapi-key": "4ffdf62c6bmshfb49ff445025abep1e2116jsn7d7aae645a00",
        },
      }
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data)
        this.basePrice = data.Quotes[0].MinPrice;
        console.log("basePrice " + this.basePrice)
      })
      .catch((err) => {
        console.log(err);
      });

    }

    this.getConnection();

    let dataStorage = {
      departureDate: this.departureDate,
      returnDate: this.returnDate,
      departureAirport: this.departureAirport,
      arrivalAirport: this.destinationAirport,
      passengersNumber: this.numberOfPassengers,
      departureAPI: this.departureAPI,
      arrivalAPI: this.arrivalAPI,
      basePrice: this.basePrice //this part is not getting into local storage

    };
    localStorage.setItem("flightdetails", JSON.stringify(dataStorage));
    this.showStorage = JSON.parse(localStorage.getItem("flightdetails"));
  }
}
2 Answers

Because you are setting dataStorage to localStorage before you got the response from the getConnection().

This is happening right now:

  1. User clicked the button ( To summary )
  2. called saving() method
  3. calling getConnection() from saving and this function is make a HTTP Request, but we dont know when the response will arrive...
  4. You are saving your values into localStorage with localStorage.setItem()
  5. We don't know when, but the API has been responded and we are setting the this.basePrice value. But we already saved the value to the localStorage.

You have to wait until you get the response from the API and set it only after that.

Summary : You should save like that after received the basePrice

  .then((data) => {
    console.log(data)
    this.basePrice = data.Quotes[0].MinPrice;
    console.log("basePrice " + this.basePrice);
    localStorage.setItem("flightdetails", dataToBeSaved);
  }) 

Or to make it more clear, you can use async / await. I have forked your project and made some changes:

With async / await

No need to use JSON.stringify. It will save your object directly and you can retrieve the same.

To Set:
localStorage.setItem("flightdetails", dataStorage );

To get:
var flightdetails = localStorage.getItem("flightdetails");

source : https://www.w3schools.com/jsref/prop_win_localstorage.asp

Related