Reputation: 1822
I originally coded this to get the first 10 albums from a rest api of albums.
constructor(props){
super(props)
this.state = { albums: [] }; // an array of objects
}
// set the first ten albums to state prop when fetched from fetch()
tenAlbums(jsonResponse) {
let tenAlbums = [];
// get just the first 10 albums from the response
for(let i = 0; i < 10; i++){
tenAlbums.push({ id: jsonResponse[i].id, title: jsonResponse[i].title })
}
this.setState({ albums: tenAlbums }); // Save as state property
}
This worked fine, until I realised I had to append to each object in the albums array, some properties of images and thumbnails from another api call. I was going to make another method like tenImages() and append them to this.state.albums. In order to do this, it looks like I'm going to have to individually inject the properties into the objects instead of my example above. I'm having trouble figuring out how to do this in React's setState. Some solutions say to make a copy of the state, make change and update it. I've tried for example
this.setState({ albums: { ...this.state.albums[i].title, title: jsonResponse[i].title} });
but this doesn't work. I guess it's something to do with the objects not being set in the first place. Any advice? Thanks.
Upvotes: 0
Views: 67
Reputation: 281
use a map function in your function tenAlbums like this:
const albums = jsonResponse.map((item) => ({
id: item.id,
title: item.title
})
map function would not mutate your original object, instead, it returns a new object. then you can use the returned object(albums in your case) to set your react state. furthermore, if you want to set other properties like thumbnails, images etc afer some other api calls, you can write another function and use react setState function like this:
this.setState(prevState => {
// you can set your other propeties here
const newAlbums = prevState.albums.map((album) => ({
...album,
thumbnail: 'some url',
image: 'some url'
}));
return newAlbums
})
Upvotes: 1