Search code examples
javascriptreactjsreact-hooksreact-functional-component

How to keep the updated state array of object values when update the same state again in React JS useState?


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

Solution

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