Link to home
Start Free TrialLog in
Avatar of Simon Leung
Simon Leung

asked on

Code in React query

For the below code in React :

Does (city,key) is the input or output parameter for the function findAirport ?
What does "then(jsonData => {this.setState({ [key]: jsonData.Places[0].PlaceId });" mean ?
Does the code inside { } is the body of the function ?
What does .then mean ?
Can I omit 'this' for "this.findAirport" ?
Where does setState function defined ?

ThxFindFlight.js

   this.findAirport = (city, key) => {
      fetch("https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/autosuggest/v1.0/US/USD/en-US/?query="+city, {
        method: "GET",
        headers: {
          "X-Mashape-Key": process.env.REACT_APP_MASHAPE_API_KEY,
          "X-Mashape-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com"
        }
      }).then(response => {
        return response.json();
      }, error =>  {
      }).then(jsonData => {
        this.setState({ [key]: jsonData.Places[0].PlaceId });
        console.log(this.state);
        if (this.state.toairport.length > 0 && this.state.fromairport.length > 0){
          this.findFlight();
        }
      })
    }

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

  this.findAirport = (city, key) => {

Open in new window

This is an arrow function - a new addition to ES6 - it is not a React specific thing - it is common to all JavaScript (ES6 and above).

This is the same as doing this
this.findAirport = function(city, key) {
  ...
}

Open in new window


then(jsonData => {this.setState({ [key]: jsonData.Places[0].PlaceId });

Open in new window

Again this is a common JavaScript function - it is the means by which the return from a Promise is handled.

If you don't know what a Promise is you can read more about it here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
In a nutshell a promise is some process that will complete some indeterminate time in the future. In asynch programming we don't want to have to wait for long asynchronous processes to complete so we wrap them in a Promise and handle the completion (resolution) of the promise when it happens by specifying a callback to invoke when the promise completes or errors out. The difference between a Promise and simply passing a callback to the asynch function is that Promises can be passed around and they can be chained which makes them very useful in this context. For example, I can create a promise around an asynchronous function and I can then pass that Promise to multiple other processes. Each of those processes can then attach their OWN .then() to the promise. So when the promise completes ALL of the attached processes get to run their own specific code on that promise.

What this code is saying is
1. Go to the specified URL and return the flight search data specified by the parameters to the URL
2. When the query completes (
.then(resp => {
});

Open in new window

which is the same as
.then(function(resp) {
});

Open in new window

Get the .json member of the response and return that to the NEXT process in the Promise chain. Refer above where I said promises can be chained. That means that when you attach to the promise resolution using then your callback function can return a value which will then be passed to the next .then() in the chain and so on. So what is happening here is we are getting a response that has a property called .json and we are passing that on to the next .then in the chain.

This is actually superfluous - we could have handled it in a single .then simply by say
jsonData = response.json

Open in new window

And then continuing with the code in the second then. The reason for the chain is the error() handler in the first .then() we want to catch an error if for whatever reason the http call failed.

The second then takes as input jsonData which is the returned response.json from the previous then.

This is the first time that React comes into the equation. The setState call is taking the returned flight search data and updating the internal model (state) with the returned data.
In this case we are specifically updating the [key] property defined by the key parameter passed into the original findAirport function.
So if we do
findAirport('CPT','ABC');

Open in new window


The search results will be saved to the following in the state
{
    ABC: placeId // search results saved here
}

Open in new window


In this case we are taking the PlaceId of the first Place in the returned JSON data (jsonData.Places[0].PlaceId ).
Avatar of Simon Leung
Simon Leung

ASKER

Can the keyword "this") be omitted since the findAirport is defined inside the FindFlight.js  ?

Thx again.

this.findAirport(this.state.fromcity, 'fromairport', this);

this.findAirport = (city, key) => {....
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial