Peter Breen
Peter Breen

Reputation: 447

Fetch/Then chain behaving strangely

I'm using a chain of then statements to transform data after a fetch request. The code is within a React app, but I think this is just a Javascript question.

Here's my current code:

componentDidMount(){

    fetch(this.state.dataRouteDirections)
        .then(data => data=data.json())
        .then(data => console.log(data))
        .then(data => data.unshift(this.state.emptyDirections))
        .then(data => this.setState({directions:data})) 
        .then(()=>{
          var makes = this.state.directions.map(directions=>directions.acf.make); //get all make categories

          function removeDuplicates(arr){
            let unique_array = arr.filter(function(elem, index, self) {
                return index===self.indexOf(elem);
              });
            return unique_array
          }

          makes = removeDuplicates(makes);
          this.setState({makes:makes});
        })    
}

The line giving me trouble is ".then(data => data.unshift(this.state.emptyDirections))". It is telling me that the variable data is undefined in this statement. Indeed, if I replace this line with the same line as above, console logging data twice, the first console log logs correctly and the second is undefined.

What am I not understanding about fetch/then/JS? I'm coming from a PHP background and async stuff is still a challenge.

Question is answered below, here's my updated code:

componentDidMount(){

    fetch(this.state.dataRouteDirections)
        .then(data => data=data.json())
        .then(data => {data.unshift(this.state.emptyDirections); return data;})
        .then(data => this.setState({directions:data})) 
        .then(()=>{
          var makes = this.state.directions.map(directions=>directions.acf.make); //get all make categories

          function removeDuplicates(arr){
            let unique_array = arr.filter(function(elem, index, self) {
                return index===self.indexOf(elem);
              });
            return unique_array
          }

          makes = removeDuplicates(makes);
          this.setState({makes:makes});
        })    
}

Upvotes: 1

Views: 88

Answers (1)

Sergii Vorobei
Sergii Vorobei

Reputation: 1487

The reason you are having this is because console.log(data) returns undefined. You should write smth like:

.then(data => {console.log(data); return data})

Upvotes: 6

Related Questions