A
A
andrey_chirkin2022-04-02 20:56:59
JavaScript
andrey_chirkin, 2022-04-02 20:56:59

How to synchronously wait for data from the server?

Hello. I have a list of cards. When you click on this Open button, its id is passed, and a transition to another page is triggered. 62488c7eb9e9f239648247.png
62488cbb2e31f439696061.png
Then it takes a lot of get requests to the server to get data from different database tables.

useEffect(() => {
    TechStore.getDataOperations(tech_id)
  }, [])

getDataOperations(tech_id) {

    let xhr = new XMLHttpRequest()

xhr.open("GET", `http://localhost:8000/api/adaptation/all`, false)

    try {
      xhr.send()
      const dataAdaptation = JSON.parse(xhr.response)

      this.dataOperations.forEach((operation) => {
        dataAdaptation.forEach((adaptation) => {
          if (adaptation["oper_id"] === operation["oper_id"]) {
            operation["adaptation"].push(adaptation)
          }
        })
      })
    } catch (err) {
      console.log(err)
    }

    xhr.open("GET", `http://localhost:8000/api/tool/all`, false)

    try {
      xhr.send()
      const dataTool = JSON.parse(xhr.response)

      this.dataOperations.forEach((operation) => {
        dataTool.forEach((tool) => {
          if (tool["oper_id"] === operation["oper_id"]) {
            operation["tool"].push(tool)
          }
        })
      })
    } catch (err) {
      console.log(err)
    }

}

How can I synchronously wait for data from the server? It turns out that this data is already being used, but it is not there yet. An error occurs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2022-04-02
@Aleksandr-JS-Developer

You don't have to wait for data synchronously, though. This degrades the UX a lot.
Usually done according to this scheme:
Request, entry loading to true ---> request completed ---> insert the data into the state and set the loading status to false.
In the template, we look at the loading status.
If true - output loader
Otherwise - data

N
Nadim Zakirov, 2022-04-03
@zkrvndm

If you need to process all requests as if it were one request, use promises to wrap requests and the Promise.all method - it will return the results of all requests at once.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question