Home > Net >  How do I make my React file sleep for 5 seconds before continuing?
How do I make my React file sleep for 5 seconds before continuing?

Time:05-25

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?

CodePudding user response:

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)

CodePudding user response:

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"]))
  • Related