Reputation: 1
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.
Upvotes: 0
Views: 361
Reputation: 105
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]);
Upvotes: 1