Deleting Data
const deleteUser = (user: User) => {
const originalUsers = [...users];
setUsers(users.filter((u) => u.id != user.id));
axios
.delete("https://jsonplaceholder.typicode.com/xusers/" + user.id)
.catch((err) => {
setError(err.message);
setUsers(originalUsers);
});
};
Adding Data
const addUser = () => {
const originalUsers = [...users];
const newUser = {
id: 0,
name: "siva",
};
setUsers([newUser, ...users]);
axios
.post("https://jsonplaceholder.typicode.com/users", newUser)
.then(({ data: savedUser }) => setUsers([savedUser, ...users]))
.catch((err) => {
setError(err.message);
setUsers(originalUsers);
});
};
Updating Data
const updateUser = (user: User) => {
const originalUsers = [...users];
const updatedUser = {
...user,
name: user.name + "!",
};
setUsers(users.map((u) => (u.id === user.id ? updatedUser : u)));
axios
.patch("https://jsonplaceholder.typicode.com/users", updatedUser)
.catch((err) => {
setError(err.message);
setUsers(originalUsers);
});
};