Reputation: 195
What's wrong with below code?
this.setState({
album: {
...this.state.album,
photos: [
...this.state.album.photos,
{ url : newUrl }
]
}
})
It worked if photos have something, but if album is an empty object, I will got this error
Cannot convert undefined or null to object
Upvotes: 1
Views: 596
Reputation: 104369
Use Short circuit evaluation concept and put ||[]
with state.albums.photos
, if albums will be blank object then (photos=undefined || [])
will return an empty array.
Use this:
this.setState(prevState => ({
album: {
...prevState.album,
photos: [
(...prevState.album.photos || []),
{ url : newUrl }
]
}
}))
Use updater function
and prevState
to compute the next state value.
Upvotes: 0
Reputation: 7424
You can also use: (...this.state.album.photos || [])
so it parses the empty array at first:
const state = {
album: {
photos: undefined
}
}
const newState = {
album: {
...state.album,
photos: [
...(state.album.photos || []),
{ url: 'newUrl' }
]
}
}
console.log(newState)
Upvotes: 3
Reputation: 2626
Yeah, that's the expected behaviour. The spread operator (...
) will spread, that is, expand everything provided. If that's null
, it can't possibly do that, right?
You can try something like:
...( Object.assign( {}, this.state.album.photos )
Upvotes: 0