KRISHNA BALLABH
KRISHNA BALLABH

Reputation: 1

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.

Upvotes: 0

Views: 361

Answers (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]);

Upvotes: 1

Related Questions