Home > Back-end >  how can i delay the server request if its being sent repeatedly in Reactjs?
how can i delay the server request if its being sent repeatedly in Reactjs?

Time:06-13

I have a checkbox input for a to-do-list app and, when I mark the task as done a request, will be sent to the server to update it but I think it can slow down the server as you can check and uncheck the input repeatedly so is there any way to delay the requests? for example, 300ms after the checkbox is changed here is my code

const [todos, setTodos] = React.useState([]);

const completedOnChangeHandler = (e, id) => {
    const x = e.target.checked;
    console.log(x);

    axios
      .patch(`http://127.0.0.1:8000/todo/todos/${id}/`, {
        completed: x,
      })
      .then(
        (response) => {
          console.log(response.data);

          setTodos([response.data]);
        },
        (error) => {
          console.log(error);
        }
      );
  };

return (
    <form>
          {todos.map((todo) => (
            <ul key={todo.id}>
              <li>{todo.title}</li>
              <li>{todo.description}</li>
              <button>delete</button>
              <input
                type="checkbox"
                placeholder="completed"
                onChange={(e) => completedOnChangeHandler(e, todo.id)}
                checked={todo.completed}
              />
            </ul>
          ))}
    </form>
  );
};

export default Form;

CodePudding user response:

You should debounce the request and disable the checkbox while the request is in progress to evade a race condition. Here is an example of a debounce function:

function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}
function saveInput(){
  console.log('Saving data');
}
const processChange = debounce(() => saveInput());

Or you can use lodash/debounce, if the lodash package is available in your project.

CodePudding user response:

You could use the debouce function from lodash or if you don't want to add the whole lib to your project, you could use: lodash.debouce

You can set the amount of time you want between requests and it will manage it for you.

CodePudding user response:

You could perhaps declare a variable/state that contains the time of the last time your input was checked.

Everytime the user check the input you compare the current time with the last time your input was checked. If the delta is superior than 300ms you send your http request.

You can use the module Date with the method Date.now(). This method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

  • Related