Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I have been placing the following code within my React JS component and I am basically trying to put both API calls into one state called vehicles however I am getting an error with the following code:

componentWillMount() {

    // Make a request for vehicle data

    axios.all([
      axios.get('/api/seat/models'),
      axios.get('/api/volkswagen/models')
    ])
    .then(axios.spread(function (seat, volkswagen) {
      this.setState({ vehicles: seat.data + volkswagen.data })
    }))
    //.then(response => this.setState({ vehicles: response.data }))
    .catch(error => console.log(error));
  }

Now I am guessing I can't add two sources of data like I have this.setState({ vehicles: seat.data + volkswagen.data }) however how else can this be done? I just want all of the data from that API request to be put into the one state.

This is the current error I am receiving:

TypeError: Cannot read property 'setState' of null(…)

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
483 views
Welcome To Ask or Share your Answers For Others

1 Answer

You cannot "add" arrays together. Use the array.concat function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) to concatenate both arrays into one and then set that as the state.

componentWillMount() {

   // Make a request for vehicle data

   axios.all([
     axios.get('/api/seat/models'),
     axios.get('/api/volkswagen/models')
   ])
   .then(axios.spread(function (seat, volkswagen) {
     let vehicles = seat.data.concat(volkswagen.data);
     this.setState({ vehicles: vehicles })
   }))
   //.then(response => this.setState({ vehicles: response.data }))
   .catch(error => console.log(error));

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...