0

I'm doing a GetList api call and after I get response I'm making another api call. dispatchUpdateHeader should happen after all the calls are done. But its not working. Is it good idea to write too many .thens?

export const getList = (data) => {
  return (dispatch) => {
    const { url, params } = GetList(data.items);
    return fetch(url, params)
      .then(() => {
        dispatch(getSavedItems(data.reqBody));
        const { url1, params1 } = UpdateItemsApi();
        return fetch(url1, params1).then(() => {
          dispatchUpdateHeader();
        });
      });
  };
};
samnu pel
  • 914
  • 5
  • 12
  • No, not the best idea it makes it too hard to tell what's going on. Your life would be alot easier if you pulled some functions out of there and defined them somewhere else so their call would be a single line, also are you defining a const getList and already have a function GetList() ? Pretty confusing if you ask me. – ruggierom May 10 '19 at 04:47

1 Answers1

0

You don't need to nest the 'then'. You would need a flat structure.

fetch(url)
.then(function(response) { 
  return response.json()
})
.then(function(data) {   
  // do stuff with `data`, call second `fetch`
  return fetch(data.anotherUrl)
})
.then(function(response) { 
  return response.json(); 
})
.then(function(data) {
  // do stuff with `data`
})
.catch(function(error) { 
  console.log('Requestfailed', error) 
});

Ref: https://stackoverflow.com/a/40981353/4452181

Ishita Singh
  • 297
  • 1
  • 6