Hello, I’ve started working on the Twitch project, however I wonder what is the best way to update my state after I’ve performed the request to the Twitch API.
Should I be pushing the new data to the array?
So far, I’m using this code to get the data (it works)
constructor(props) {
super(props);
this.state = {
users: ['esl_csgo', 'Bajheera', 'Swifty']
}
}
componentWillMount() {
const TWITCH_API = 'https://api.twitch.tv/kraken/users/';
const CLIENT_ID = '?client_id=XXXX';
let { users } = this.state;
for (let i = 0; i < users.length; i++) {
axios.get(`${TWITCH_API}${users[i]}${CLIENT_ID}`)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
}
}
Then how should I go about updating each one of them? What is the best method?
I thought about renaming it to names
and then create a new array streamers
, then, every time I do a request, I would copy the previous state ...state
and append the data from the request.
What do you guys think about this approach?
EDIT: This I what I ended up doing, not sure if it’s correct:
constructor(props) {
super(props);
this.state = {
users: ['esl_csgo', 'Bajheera', 'Swifty'],
streamers: []
}
}
componentWillMount() {
const TWITCH_API = 'https://api.twitch.tv/kraken/users/';
const CLIENT_ID = '?client_id=XXXX';
let { users } = this.state;
for (let i = 0; i < users.length; i++) {
axios.get(`${TWITCH_API}${users[i]}${CLIENT_ID}`)
.then(res => {
this.state.streamers.push(res.data);
console.log(res);
})
.catch(err => {
console.log(err);
})
}
}