zemmsoares
zemmsoares

Reputation: 353

ReactJS fetch for each value of array

I have a Multi-Select

enter image description here

The select saves the values into a string separeted by commas, soo i use zag() to transform the string into an array

this.state.value: zemm,lena

After zag():

cleanArray : ["zemm","lena"];

After having a clean array i was trying to fetch data for each value in the array, my idea was concatenating the data for every name selected. But once i remove values from the array the Data keeps multiplicating.

If i select "zemm" which lets say it has an array of 10 objects [{...},{...}..]. and then remove it, i end up with 20 objects, if i add it again, 30 objects ...

 zag(){
    const arrayMessy = this.state.value +'';
    var arraySplit = [];
    arraySplit = arrayMessy.split(',');
    this.setState({cleanArray: arraySplit},() => this.zag2());
  }

  zag2(){
    var arrayLimpo = this.state.cleanArray;
    for (var i = 0; i < arrayLimpo.length; i++) {
      const url = 'http://localhost:8000/issues/assigned/';
      const value = arrayLimpo[i];
      const string = url+value+'&maxResults=5000';
      fetch(string)
      .then(function(response) {
        return response.json();
      })
      //.then((myJson) => this.setState({data: myJson.issues}));
      .then((myJson) => this.setState({ data: this.state.data.concat(myJson.issues)}));
      }
    }

Any help appreciated! Thanks

Upvotes: 0

Views: 43

Answers (1)

kristaps
kristaps

Reputation: 1723

Your code seems to have the correct but commented out version right above the line which causes problems. Your data is multiplying because you concatenate whatever the server returned to whatever was already there - the existing data array is not cleared between requests.

Edit: Understood the problem now, you could change

this.setState({cleanArray: arraySplit},() => this.zag2());

to

this.setState({cleanArray: arraySplit, data: []},() => this.zag2());

then it would work as you expect.

Upvotes: 1

Related Questions