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

179
Visualizações
React time based function

I am trying to create an api post function that sends when the timeout reaches 45 seconds and when the user clicks the cancel button the post request stops or you clear the timeout to stop it. I did something that works but after another 45 secs it makes another post requirement. is there way to make the post request after the 45 seconds and then cancel the request when user clicks the cancel button

import { makeStyles } from "@material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'


const useStyles = makeStyles(styles);

function processorder({ query: { name, number, location, ordermessage, price, } }) {
    const classes = useStyles();

    const [processed, setProcessed] = useState(false)
    const [canceled, setCanceled] = useState(false)
    const [time, setTime] = useState()
    const [data, setData] = useState({})

    const Id = setTimeout(() => {

        const requestOptions = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'Api-key': 'ml7h7L8nN8Q2yA',
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "X-Requested-With"
            },
            body: JSON.stringify({
                client: name,
                client_phone: number,
                restaurant: "Chitis",
                location: location,
                ordermessage: "Jollof Rice",
                amount: "500"
            })
        };
        fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result)
                setData(result.data)
                setProcessed(true);
                return () => clearTimeout(Id)
            })
            .catch(error => console.log('error', error));



    }, 45000);


    const cancel = () => {


        clearTimeout(Id);
        setCanceled(true);
        if (canceled == true) {
            alert("canceled")
        }
    };






    return (

       <div>

        <h3> processing Order<h3>
          (processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding      to payment</h3>)

(canceled == false ? (<Button  onClicK={cancel} />) : <h3>order canceled</h3>


       
      </div>
    )
}
processorder.getInitialProps = ({ query }) => {
    return { query }
};

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

0

You could wrap your whole timeout function in an if, which is dependant on state. However, this isn't very robust as changing the data or the time also sends a duplicate request:

import { makeStyles } from "@material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'


const useStyles = makeStyles(styles);

function processorder({ query: { name, number, location, ordermessage, price, } }) {
    const classes = useStyles();

    const [processed, setProcessed] = useState(false)
    const [canceled, setCanceled] = useState(false)
    const [time, setTime] = useState()
    const [data, setData] = useState({})

    if (!canceled && !processed) {

      const Id = setTimeout(() => {

        const requestOptions = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'Api-key': 'ml7h7L8nN8Q2yA',
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "X-Requested-With"
            },
            body: JSON.stringify({
                client: name,
                client_phone: number,
                restaurant: "Chitis",
                location: location,
                ordermessage: "Jollof Rice",
                amount: "500"
            })
        };
        fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result)
                setData(result.data)
                setProcessed(true);
                return () => clearTimeout(Id)
            })
            .catch(error => console.log('error', error));



      }, 45000);
    }


    const cancel = () => {


        clearTimeout(Id);
        setCanceled(true);
        if (canceled == true) {
            alert("canceled")
        }
    };






    return (

       <div>

        <h3> processing Order<h3>
          (processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding      to payment</h3>)

(canceled == false ? (<Button  onClicK={cancel} />) : <h3>order canceled</h3>


       
      </div>
    )
}
processorder.getInitialProps = ({ query }) => {
    return { query }
};

export default processorder

It would probably be better for you to do the whole fetch & timeout inside a clickHandler, with the timeout checking that canceled is false before sending the request.

about 4 years ago · Juan Pablo Isaza Relatório

0

import { makeStyles } from "@material-ui/core/styles";
import styles from "styles/jss/nextjs-material-kit/pages/components.js";
import Button from "components/CustomButtons/Button.js";
import Time from "components/Time.js"
import { withRouter } from 'next/router'


const useStyles = makeStyles(styles);

function processorder({ query: { name, number, location, ordermessage, price, } }) {
    const classes = useStyles();

    const [processed, setProcessed] = useState(false)
    const [canceled, setCanceled] = useState(false)
    const [time, setTime] = useState()
    const [data, setData] = useState({})
    const [id, setId] = useState()

    const cancel = () => {
        clearTimeout(id);
        setCanceled(true);
        if (canceled == true) {
            alert("canceled")
        }
    };

    useEffect(() => {
        const Id = setTimeout(() => {

            const requestOptions = {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                    'Api-key': 'ml7h7L8nN8Q2yA',
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Headers": "X-Requested-With"
                },
                body: JSON.stringify({
                    client: name,
                    client_phone: number,
                    restaurant: "Chitis",
                    location: location,
                    ordermessage: "Jollof Rice",
                    amount: "500"
                })
            };
            fetch('https://munche-bot.herokuapp.com/api/v1/orders', requestOptions)
                .then(response => response.json())
                .then(result => {
                    console.log(result)
                    setData(result.data)
                    setProcessed(true);
                    clearTimeout(Id);
                })
                .catch(error => console.log('error', error));



        }, 45000);
        setId(Id);

        console.log(data)
    }, []);





    
    return (

       <div>

        <h3> processing Order<h3>
          (processed == false ? (<h3>proceed to payment in <Time/> <h3>) : (<h3>processed proceeding      to payment</h3>)

(canceled == false ? (<Button  onClicK={cancel} />) : <h3>order canceled</h3>


       
      </div>
    )
}
processorder.getInitialProps = ({ query }) => {
    return { query }
};

export default processorder
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