javascript - How to setState on specific item in array? -


in app, fetch data api , put in state of component.

this.state = {    contributors: [],  }    componentdidmount() {    axios.get(data)          .then(res => this.setstate({contributors: res})  }

this.state.contributors array of objects. each 1 of objects has 3 properties values 3 api calls.

0: {  "name": "thiscontributor",  "followers_url": "https://api.github.com/users/thiscontributor/followers",  "gists_url": "https://api.github.com/users/thiscontributor/gists",   "repos_url": "https://api.github.com/users/thiscontributor/repos",   }

now need iterate over, 100 contributors (or of them makes load time long) , update each contributor length of response. thinking add properties holding these lengths:

0: {  "name": "thiscontributor",  "followers_url": "https://api.github.com/users/thiscontributor/followers",  "gists_url": "https://api.github.com/users/thiscontributor/gists",  "repos_url": "https://api.github.com/users/thiscontributor/repos",  "followers": -length of followers_url api response-,  "gists": -length of gists_url api response-,  "repos": -length of repos_url api response-  }

but doesn't work:

for (let = 0; < 100; i++) {    axios.get(`${this.state.contributors[i].followers_url}?per_page=100&${api_key}`)     .then(res => {      this.setstate({contributors[i].followers: res.data.length})    }  }

how fix that, can update followers, gists , repos?

try this

for (let = 0; < 100; i++) {   axios.get(`${this.state.contributors[i].followers_url}?per_page=100&${api_key}`)    .then(res => {     let tmp = [...this.state.contributors];     tmp[i].followers = res.data.length     this.setstate({contributors: tmp})   } } 

update:

fetch = (url, propertyname) => {     (let = 0; < 100; i++) {         axios.get(url)          .then(res => {             let tmp = [...this.state.contributors];             tmp[i][propertyname] = res.data.length             this.setstate({contributors: tmp})         }     } } ... fetch(`${this.state.contributors[i].followers_url}?per_page=100&${api_key}`, "followers") fetch(`${this.state.contributors[i].gists_url}?per_page=100&${api_key}`, "gists") fetch(`${this.state.contributors[i].repos_url}?per_page=100&${api_key}`, "repos") 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -