I'm using React functional component and obviously, the useState hook helps to create and update the state values. I commonly wrote the update functionality in a function to update an array of objects. When I update, it updates the value and when I again called the same function to update some other value it updates properly but the previously updated value went back to the old value and it doesn't retain the updated value.
const updateTranslatedResponse = (segmentId, key, value) => {
setTranslatedResponse(
translatedResponse.map(
el => el.segment_id == segmentId ? { ...el, [key]: value }: el
)
)
}
Use prev
parameter in useState hook. The useState
hook is asynchronous.
const updateTranslatedResponse = (segmentId, key, value) => {
setTranslatedResponse( prevTranslatedResponse =>
prevTranslatedResponse.map(
el => el.segment_id == segmentId ? { ...el, [key]: value }: el
)
)
}