T
T
TheRevan2018-06-17 12:53:45
JavaScript
TheRevan, 2018-06-17 12:53:45

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));
  }

response.json()) - returns data in this format: image.png
How do I add a username to the order from another request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-06-17
@TheRevan

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
  }
}

I
Ihor Bratukh, 2018-06-17
@BRAGA96

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 question

Ask a Question

731 491 924 answers to any question