Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!