Alex Yong
Alex Yong

Reputation: 7645

SetState to push new data to the state array object

I want to do a POST to an API endpoint, there's a field called space_photos, it accept array of objects.

this is my callback func whenever user uploaded a photo.

constructor(){
this.space_photo_holder = [];
}

callback = (e) => {

    this.space_photos_holder.push(e);

    this.setState({space_photos: this.space_photos_holder})

}

I think the code is legit but is there any better way to do it?

Upvotes: 0

Views: 1136

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282120

You can simply use concat instead of push. It returns a updated array

constructor(){
    this.state = {
      space_photos= []
    }
}

callback = (e) => {

    this.setState({space_photos: this.state.space_photos.concat(e)})

}

Upvotes: 1

Tharaka Wijebandara
Tharaka Wijebandara

Reputation: 8065

You can simply use spread operator. It's recommended to set initial state in constructor and use the functional version of setState when the new state is based on the previous state.

constructor(){
  this.state = { space_photos: [] };
}

callback = (e) => {
  this.setState((state) => { space_photos : [...state.space_photos, ...e]})
}

Also, you can use cancat method.

callback = (e) => {
  this.setState((state) => { space_photos : state.space_photos.cancat([e]) });
}

Upvotes: 1

Related Questions