In the Creating Data video of Connecting to the Backend, Mosh does this:
const addUser = () => {
const originalUsers = [...users];
const newUser = { id: 0, name: "Mosh" };
setUsers([newUser, ...users]);`
axios
.post("https://jsonplaceholder.typicode.com/users", newUser)
.then(({ data: savedUser }) => setUsers([savedUser, ...users]))
.catch((err) => {
setError(err.message);
setUsers(originalUsers);
});
};
Why is the new user being added to the state variable twice?
setUsers([newUser, ...users]);
setUsers([savedUser, ...users])
This doesn’t actually add it twice in practice but I think that is only because React updates state variables asynchronously.
Is this a mistake or am I missing something?