skip to Main Content

I’m building a Todo application using the MERN stack (MongoDB, Express.js, React, Node.js), and I have a question about best practices for maintaining data consistency between frontend and backend after DELETE operations.

Currently, after deleting a todo item, I’m updating the frontend state like this:

  const handleToggleDone = async (id, isDone) => {
    try {
      const { data } = await axios.put(`http://localhost:5001/api/todos/${id}`, { isDone });
      setTodos(todos.map(todo => todo._id === id ? data : todo));
    } catch (err) {
      console.error('Error updating todo status:', err);
    }
  };

Instead of filtering the local state, I’m wondering if I should refetch all todos from the database to ensure perfect consistency:

const handleDelete = async (id) => {
  try {
    await axios.delete(http://localhost:5001/api/todos/${id});
    // Should I do this instead?
    const {data} = await axios.get('http://localhost:5001/api/todos');
    setTodos(data);
  } catch (err) {
    console.error('Error deleting todo:', err);
  }
};

My concerns are:

  1. Performance impact of additional API calls
  2. Data consistency in case of concurrent users
  3. Best practices for CRUD operations in MERN stack

Which approach is considered better practice? Are there any potential issues I should be aware of with either approach?

2

Answers


  1. It’s completely depends on your entire codes.
    For example, the optimal answer would vary depending on factors such as the specific MongoDB schema implementation, the amount of data stored in MongoDB, and how frequently the data is updated.

    If you can, I would like to see your related codes.

    Login or Signup to reply.
  2. For update consistency

    Consider a case, an item the user under the context is deleting has already been deleted by another user sometime ago. In such a case, the App should detect the same and communicate the same appropriately to the user. This is the kind of update consistency it is expected.

    Similarly for while saving changes to an item, if the same item has been already been updated by another user, then the App should detect the same and communicate it to the user. In such a case, the current user’s save request should be aborted, and he/she should be requested to view the latest data and make another attempt to change the item.

    For Read consistency

    The list of items displayed in the App is always with respect to the time of its retrieval. Therefore the App should make the time of retrieval visible to the user. This piece of information would give its users a sense of Read consistency.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search