Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

300
Visualizações
how can i delay the server request if its being sent repeatedly in Reactjs?

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;
about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

You should debounce the request and disable the checkbox while the request is in progress to avoid 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.

about 4 years ago · Santiago Gelvez Relatório

0

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.

about 4 years ago · Santiago Gelvez Relatório

0

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.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda