1

https://codesandbox.io/s/redux-async-actions-xjdo7

<FetchButton
          onFetchClick={() => {
            store.dispatch(dispatchFunc => {
              dispatchFunc({ type: "FETCH_DATA_START" });
              axios
                .get("https://reqres.in/api/users?page=2")
                // axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => {
                  console.log("response.data.data---->", response.data.data);
                  console.log(
                    "response.data.data[0].id---->",
                    response.data.data[0].id
                  );
                  dispatchFunc({
                    type: "RECEIVED_DATA",
                    payload: response.data.data
                  });

                  let firstAPIid = response.data.data.map(obj => {
                    return obj.id;
                  });
                  console.log("firstAPIid---->", firstAPIid);

                  return new Promise((resolve, reject) => {
                    //var url = `https://jsonplaceholder.typicode.com/comments?postId=3`;
                    var url =
                      `https://jsonplaceholder.typicode.com/comments?postId=` +
                      firstAPIid;
                    //response.data.data[0].id;

                    console.log("second url---->", url);

                    axios
                      .get(url)
                      .then(response => {
                        var lFilterData = "";
                        //memberGroupingHelper.filterData(response.data, additionalParams);
                        resolve(lFilterData);
                      })
                      .catch(error => {
                        if (error.response) {
                          console.log(
                            `@@@@@@@@@@@@@@ service error from helpeeeeeer reject`
                          );
                        }
                        reject("");
                      });
                  });
                })
                .catch(err => {
                  dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
                });
            });
          }}
        />

1 Answers1

1

I found your issue. It is happening because you are not processing the result of the promise. To do that just add the .then() and .catch() functions:

<FetchButton
          onFetchClick={() => {
            store.dispatch(dispatchFunc => {
              dispatchFunc({ type: "FETCH_DATA_START" });
              axios
                .get("https://reqres.in/api/users?page=2")
                // axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => {
                  console.log("response.data.data---->", response.data.data);
                  console.log(
                    "response.data.data[0].id---->",
                    response.data.data[0].id
                  );
                  dispatchFunc({
                    type: "RECEIVED_DATA",
                    payload: response.data.data
                  });

                  let firstAPIid = response.data.data.map(obj => {
                    return obj.id;
                  });
                  console.log("firstAPIid---->", firstAPIid);

                  return new Promise((resolve, reject) => {
                    //var url = `https://jsonplaceholder.typicode.com/comments?postId=3`;
                    var url =
                      `https://jsonplaceholder.typicode.com/comments?postId=` +
                      firstAPIid;
                    //response.data.data[0].id;

                    console.log("second url---->", url);

                    axios
                      .get(url)
                      .then(response => {
                        var lFilterData = "";
                        //memberGroupingHelper.filterData(response.data, additionalParams);
                        resolve(lFilterData);
                      })
                      .catch(error => {
                        if (error.response) {
                          console.log(
                            `@@@@@@@@@@@@@@ service error from helpeeeeeer reject`
                          );
                        }
                        reject("");
                      });
                  }).then((previousResponse) => {
                    //Here you resolved the promise with the resolve value above
                    console.log(previousResponse)
                  }).catch((error) => {
                    //Here you resolved the promise with the reject value above
                    console.log(error);
                  });
                })
                .catch(err => {
                  dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err });
                });
            });
          }}
        />

I am not seeing any use of the Promise because what you want to achieve can be done just with axios.

EDIT: Just with axios you can get it. Modify as below:

<FetchButton
        onFetchClick={() => {
            store.dispatch(dispatchFunc => {
              dispatchFunc({ type: "FETCH_DATA_START" });
              axios
                .get("https://reqres.in/api/users?page=2")
                // axios.get('https://jsonplaceholder.typicode.com/posts')
                .then(response => {
                  console.log("response.data.data---->", response.data.data);
                  console.log(
                    "response.data.data[0].id---->",
                    response.data.data[0].id
                  );
                  //First of all we'll create the number of requestes base on the previous Response
                  const promises = response.data.data.reduce((previousValue, { id }) => { 
                    previousValue.push(axios.get(`https://jsonplaceholder.typicode.com/comments?postId=${id}`));
                    return previousValue;
                  },[]);
                  //We use the built in function to fetch the data
                  axios.all(promises)
                    .then((responses) => {
                      //Here you have all responses processed
                      const emailsMapped = responses.reduce((previousValue, { data }) => {
                        const emails = data.map(({ email }) => email)
                        previousValue.push(...emails);
                        return previousValue;
                      }, [])
                      //You send the emails you want  
                      dispatchFunc({
                          type: "RECEIVED_DATA",
                          payload: emailsMapped
                        });
                      console.log(emailsMapped);
                    })
                })
                .catch(err => {
                  dispatchFunc({ type: "FETCH_DATA_ERROR", payload: err }); 
                });
            }); 
          }}
        />

Also modifies this line in DataList without the first_name

listItems.push(<div key={fetchedDataId++}>{elem}</div>);
Sergio Escudero
  • 1,798
  • 14
  • 21
  • hey I ran your updated code, but still I am getting issues it should be print like this `second url----> https://jsonplaceholder.typicode.com/comments?postId=4` but still printing as combined values `second url----> https://jsonplaceholder.typicode.com/comments?postId=4,5,6` can you update in my sandbox https://codesandbox.io/s/redux-async-actions-xjdo7 –  Jul 18 '19 at 19:28
  • Do you want to print the response of the second API call? or what do you want to show in the screen ? – Sergio Escudero Jul 18 '19 at 19:44
  • I need to pass this firstAPIid from first api to the second api and print the response in the browser –  Jul 18 '19 at 19:58
  • Which response ? – Sergio Escudero Jul 18 '19 at 19:58
  • The response from this call ? `https://jsonplaceholder.typicode.com/comments?postId=+firstAPIid;` – Sergio Escudero Jul 18 '19 at 19:59
  • With the current values you are sending the response is an empty array [] – Sergio Escudero Jul 18 '19 at 20:02
  • 1
    yeah thats the bug we need to fix, instead of passing as 4,5,6 we need to pass 4 separately like this https://jsonplaceholder.typicode.com/comments?postId=4 and 5 sperately like this https://jsonplaceholder.typicode.com/comments?postId=5 –  Jul 18 '19 at 20:10
  • @zizi check the edit. I also modified your sandbox. I just mapped the emails, if you want the whole result skip that part – Sergio Escudero Jul 18 '19 at 20:43
  • hey but those values are not showing in the browsers https://codesandbox.io/s/redux-async-actions-xjdo7 –  Jul 18 '19 at 20:47
  • @zizi somehow the changes are not kept – Sergio Escudero Jul 18 '19 at 20:47
  • hey instead of reduce cant we use map method :( can you explain it will help me to understand better :( –  Jul 19 '19 at 13:42
  • hey can you tell me why your using empty array in the end of reduce method it to make as an previousValue array `const emailsMapped = responses.reduce( (previousValue, { data }) => { console.log("2 data---->", data); const emails = data.map(({ email }) => email); previousValue.push(...emails); return previousValue; }, [] );` –  Jul 19 '19 at 15:08
  • For sure @zizi, this empty array is the initial value for the previousValue. This function iterate over an array and the previous value is the value returned in the body function. so the first iteration the previousValue has an empty array `[]` and the `{data}` value has the first element that we are iterating. as you see we are pushing and then returning so in the second iteration will be an array with a data value `[data]` and the `{data}` value will be the second value of the iteration and so on – Sergio Escudero Jul 19 '19 at 18:27
  • hey for performance map or reduce is good? and do we need to use async? –  Jul 19 '19 at 18:52
  • @zizi I have no measures for that question but you can check some differences here [reduce vs map](https://stackoverflow.com/questions/49934992/main-difference-between-map-and-reduce) – Sergio Escudero Jul 19 '19 at 21:14