I'm trying to update an array from a put request
const [descriptors, setDescriptors] = useState([]);
const handleDescriptorUpdate = (id, descriptorData) => {
services
.putDescriptor(id, descriptorData)
.then((response) => {
const descriptorIndex = _.findIndex(descriptors, (e) => e.id === id);
if (descriptorIndex !== -1) {
const tempDescriptors = [...descriptors];
tempDescriptors[descriptorIndex] = response.data;
setDescriptors(tempDescriptors);
}
})
.catch((error) => {
console.error(error);
});
};
This works fine when I perform only 1 request at the time, but when I click the button that performs the update twice the promises, instead of spreading the array and updating the old value with the new one, both of them are spreading the same array causing that when the second promise is resolved, it updates the state with the new value (second value) that came back from the server BUT changing the first value (the one changed by the first promise) for its original value.
Descriptors are initially filled with an array of objects (from a get request):
[
{
"id": 24,
"name": "Test 4.1",
"percentage": 0,
"towerId": "5cfc9200-c04a-11e9-89c0-2dd5d3707b1b"
},
{
"id": 23,
"name": "Test 3.1",
"percentage": 0,
"towerId": "5cfc9200-c04a-11e9-89c0-2dd5d3707b1b"
}
]