简体   繁体   中英

React - How to sync front-end with back-end requests without using setTimeout?

When I'm trying to do a validation in react JS I normally have to create a set time out function to sync the fetch api calls with front end as the fetch api calls take a bit of time. Is there are any other way to do this? Something that's under best practices and not recurring codes?

I have been using set time out with 4000-5000, it works, but i feel as if that's not the best way to do so.

edit- Below is the code snippet of what i did before using timeout, but for some reason when the function runs, 'existingTrains' disappears from state.

async getExistingReservations(date, trackNo, direction, noTickets) {

        let self = this;
        var trains;
        var ticketRange = 100 - noTickets;

        var data = {
            "date": date,
            "trackNo": trackNo,
            "direction": direction
        }

        console.log(data);

        //get Existing Reservation Details
        await fetch('http://localhost:5000/resRecords/getSeats', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {'Content-Type': 'application/json'}
        })
            .then(response => {
                return response.json()
            })
            .then(json => {
                console.log(json)
                trains = json.find(function (tickets) {
                    return tickets.noTickets < ticketRange

                })
                self.setState({
                        existingTrains: trains
                    }
                )
            });

    }

The best way to resolve this is by using async -> await .

const getNetworkRequest = async (): string => {
  const r = await makeNetworkRequest();
  console.log(r);

  if(r.data){ return 'got it!' } 
  return 'no data :(';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM