'Why it is appending the Previous object to array when i append the new object to it using useState hook?
const [arr, setArr] = useState([])
const obj = {userName: "ABCD", password: "123245"};
setArr(prevState => [...prevState,obj]);
I am writing this to append a new object to array but array is not directly updated. it append the previous object when i want to append the new object to it means it is working one step behind.
Solution 1:[1]
You can just use the previous state of the array to add the new object and store it in the state like this:
const [arr, setArr] = useState([]);
const obj = {userName: "ABCD", password: "123245"};
setArr([...arr, obj]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Fernández Flores |
