0

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?

2 Answers 2

1

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)})

}
Sign up to request clarification or add additional context in comments.

2 Comments

just tried this and this won't work, the array will always be one. I want to push array not replace them.
You are right that wouldnt have worked since you were not changing the space_photos_holder array. Use the updated approach
1

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]) });
}

1 Comment

concat is cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.