Home > Software design >  Deleted users disappearing after refreshing the page not real time in react
Deleted users disappearing after refreshing the page not real time in react

Time:09-22

I wanted to select multiple users from table and delete them with real time . When i check db it is deleting selected users but from front end with react it is happening after refreshing the page. Can anyone help me? Here is my FE code:

const handleDeleteUser = async () => {
    const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
      method: "DELETE",
      body: JSON.stringify(isChecked),
      headers: {
        "Content-Type": "application/json",
      },
    });
    if(response.status === 200){
      const data = await response.json()
      for (let i = 0; i < data.length; i  ) {
        const element = data[i];
        setUsers(users.filter((e) => e._id !== element))
        console.log("DELETED ELEMENT",element);
      }
    }
  };

BE code:

userRouter.delete("/deleteUsers", async (req, res, next) => {
  try {
    const selectedUsers = req.body;
    // HARD DELETE
    UsersModel.deleteMany(
      {
        _id: {
          $in: selectedUsers,
        },
      },
      function (err, result) {
        if (err) {
          res.status(404).send(err);
        } else {
          res.status(200).send(selectedUsers);
        }
      }
    );
  } catch (error) {
    next(error);
  }
});

CodePudding user response:

Whenever we manage data on react app so we call it state management. There're some tools & packages to handle state management in react like redux-toolkit and react-query.

Now your issue is that data isn't persistent and to make this data persistent you can use plenty of options some of them are redux-toolkit-persistent and react-query.

CodePudding user response:

you're totally wrong about the way handle setState. setState can't be multiple in single context like for-loop because setState update the state after re-rendering. Try this way.

const data = await response.json()

setUsers(users.filter(user => !data.find(row => row.id === user.id)))//don't know your properties adjust this code on yourown.

console.log("DELETED ELEMENT", data);
      

I think you should check out the reference for understanding how state works in react.

  • Related