In my React application, I have an array of objects implemented using a "useState" hook. The idea is to update an existing object within this array if an object with a specific "id" already exists or to add a new object if it does not.
The problem that I am encountering is that my state is not up-to-date before I am modifying it (= updating and/or adding objects). Therefore, the check whether an object with a certain "id" already exists fails.
Here is a (very much simplified) example demonstrating the problem:
import React, { useEffect, useState } from 'react';
interface Dummy {
id: string;
value: number;
}
const TestComponent = () => {
const [dummies, setDummies] = useState<Dummy[]>([]);
const addDummy = (id: string, value: number) => {
const dummyWithIdAlreadyUsed = dummies.find(
(dummy: Dummy) => dummy.id === id
);
if (!dummyWithIdAlreadyUsed) {
setDummies((dummies) => [...dummies, { id: id, value: value }]);
}
};
const test = () => {
addDummy('dummy1', 1);
addDummy('dummy1', 2);
addDummy('dummy2', 3);
addDummy('dummy2', 4);
addDummy('dummy3', 5);
addDummy('dummy4', 6);
addDummy('dummy4', 7);
};
useEffect(() => {
console.log(dummies);
}, [dummies]);
return <button onClick={test}>Test!</button>;
};
export default TestComponent;
The desired output is:
0: Object { id: "dummy1", value: 1 }
1: Object { id: "dummy2", value: 3 }
2: Object { id: "dummy3", value: 5 }
3: Object { id: "dummy4", value: 6 }
The actual output is:
0: Object { id: "dummy1", value: 1 }
1: Object { id: "dummy1", value: 2 }
2: Object { id: "dummy2", value: 3 }
3: Object { id: "dummy2", value: 4 }
4: Object { id: "dummy3", value: 5 }
5: Object { id: "dummy4", value: 6 }
6: Object { id: "dummy4", value: 7 }
How can I make sure that my state is up-to-date before executing setDummies
?