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

366
Visualizações
How do I make my React file sleep for 5 seconds before continuing?

So I want to make my function delay reading lines before navigating to another page. I have a microservice currently running on an infinite loop which reads and writes from a text file. Since the process can take a while, I would like to wait at least 5 seconds. Here's my code:

import { Link } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import React from "react";
import axios from "axios";
import raw from '../command_file.txt';

function HomePage() {
    let navigate = useNavigate();
    let result;

    const [ingredientInput, setIngredientInput] = React.useState();

    const handleSubmit = async (e) => {
        e.preventDefault();
        const data = {ingredientInput};
        console.log(data.ingredientInput);
        console.log(JSON.stringify(data));
        const response = await fetch('http://localhost:5000/verify', {
            method: 'POST',

            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });
        if (response.status === 201){
            console.log("Connected to microservice!");
        } else {
            console.log(`Error, status code = ${response.status}`)
        }
        console.log(JSON.stringify(response.json));
        fetch(raw)
            .then(r => r.text())
            .then(text => {
                console.log('text decoded:', text);
                console.log(text[7]);
                result = text[7];
                navigate("/result", result);
        });
    
    };

I want to be pause the program before fetch is called by 5 to 10 seconds so result can be populated by a variable in which the file can later pass on the result using navigate. Unfortunately, I haven't been able to get anything like setTimeout working. As the program runs now, result ends up being passed as undefined and the variable text returns old data from the text file. I am out of ideas, would anyone be able to point me in the right direction as to what I need to do?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I am not quite sure if this would help in your case, but you can use this cool manual js sleep function:

const sleep = ms => new Promise(r => setTimeout(r, ms));

and then before the fetch, you can call it like:

await sleep(5000)

about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not sure I understand what you're building here, but it seems like you're using that public .txt file as a database, which is really not a good idea. Ideally you want your microservice to write to the database and return whatever your frontend code needs directly.

In your case the flow could look like this:

  1. You send the ingredients list to the microservice
  2. The microservice does all the necessary calculations and inserts the data into a database (e.g. SQLite or PostgreSQL)
  3. The microservice then returns the redirect URL directly

You code would then look something like this:

fetch('http://localhost:5000/verify', { ...postHeaders }).then(
    res => res.json()).then(res => navigate(res["url"]))

Edit: If you really must do it this way, I'd look at the way you're importing the txt file. You need to make sure it's in a public directory (e.g. can be served by nginx) and that you actually fetch it from that public URL as opposed to importing it at build time. However, I'm still not sure why they make you do it this way as it really doesn't make much sense.

about 4 years ago · Juan Pablo Isaza 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