( sorry for poor wording on the title... couldn't find a good way to word it. )
I have a method that does a put request and then updates the state.
In the example below, key_in_state
are dictionaries with unique ids as the key. It checks if the dictionary contains the old response data. If it does, update that specific one.
method_name = () => {
let key_in_state_1 = { ...this.state.key_in_state_1 }
let key_in_state_2 = { ...this.state.key_in_state_2 }
axios.put( someurl )
.then( res => {
if ( key_in_state_1[ res.data._id ] ) {
key_in_state_1[ res.data._id ] = res.data
}
if ( key_in_state_2[ res.data._id ] ) {
key_in_state_2[ res.data._id ] = res.data
}
this.setState( {
key_in_state_1,
key_in_state_2
} )
} )
}
Would it be more efficient to call this.setState
a single time as shown in the example above or would it be better to call this.setState
within each if statement so we wouldn't need to rewrite the state if there is no new data?
method_name = () => {
let key_in_state_1 = { ...this.state.key_in_state_1 }
let key_in_state_2 = { ...this.state.key_in_state_2 }
axios.put( someurl )
.then( res => {
if ( key_in_state_1[ res.data._id ] ) {
key_in_state_1[ res.data._id ] = res.data
this.setState( { key_in_state_1 } )
}
if ( key_in_state_2[ res.data._id ] ) {
key_in_state_2[ res.data._id ] = res.data
this.setState( { key_in_state_2 } )
}
} )
}
Sometimes the response isn't within the the dictionaries so we wouldnt even need to update it.
Thank you!