Answer the question
In order to leave comments, you need to log in
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.
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)
}
}
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question