Answer the question
In order to leave comments, you need to log in
How to make a linked request via fetch and link orders to users?
There is such a code
componentDidMount = () =>{
let token = 'Bearer ' +localStorage.getItem('token');
console.log(token);
fetch('*****************', { method: 'GET',headers:{'Accept': "application/json", "Authorization": token}})
.then(response => response.json())
.then((response) => {
let orderArr = response.success.orders;
orderArr.forEach(order => {
///return fetch('**************'+order.user_id, { method: 'GET',headers:{'Accept': "application/json", "Authorization": token}})
});
})
.then((response) => console.log(response))
.catch(error => console.log(error));
}
Answer the question
In order to leave comments, you need to log in
If you display the username in the lists, then the best option would be to add the user to each order in the linked field on the server . This way you will get all the necessary data in one request.
Or, something like:
componentDidMount() {
this.fetchData();
}
async fetchData() {
try {
const orders = await fetch('orders-path', options).then(response => response.json());
const users = {};
for (let i = 0; i <= orders.length; i++) {
const id = orders[i].user_id;
const user = await fetch('/user/' + id, options).then(response => response.json());
users[id] = user;
}
this.setState({ orders, users });
} catch (e) {
// handle error
}
}
async/await, promise, promise.all
An example on codepen.io
In this example, first there is a request for one endpoint, in the response we get data and links to which we need to throw the following requests.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question