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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With