Home > Net >  I'm trying to chain 2 fetch requests together, using the data from the first one in the second
I'm trying to chain 2 fetch requests together, using the data from the first one in the second

Time:03-26

Im trying chain 2 fetch requests together, mapping over the data (partner.Id) from the first one to make a fetch request for each partner.Id and returning them in a list to display in my NextJS page. Any help would be much appreciated.

this is my fetch request which im trying to send over to my next page, it is most likely done incorrectly so help would be good. I want to return something like 'CustomerResponse' from the second fetch:

export async function getStaticProps() {
  const partnerRes = await fetch(
    `${process.env.REACT_APP_REQUESTURI}/api/Partners`,
    {
      headers: {
        Authorization: "Bearer "   process.env.REACT_APP_ACCESS_TOKEN,
        "Content-Type": "application/json",
      },
    }
  ).then(partnerRes => {
    return partnerRes.json();
  }).then((data) => {
      return data.map((partner: { Id: any }) => {
          return fetch(
            `${process.env.REACT_APP_REQUESTURI}/api/Partners/${partner.Id}/Customers`,
            {
              headers: {
                Authorization: "Bearer "   process.env.REACT_APP_ACCESS_TOKEN,
                "Content-Type": "application/json",
              },
            }
          );
        })
    });
}

This is my next page, although I havent really done much on it yet as im focusing on the fetch requests.

return (
    <div className="App">
      <div>
      <ul className="customers">
        <input
          type="search"
          value={name}
          onChange={filter}
          className="input"
          placeholder="Customer Name"
        />
        {foundCustomers && foundCustomers.length > 0 ? (
          foundCustomers.map((customer) => (
            <form method="POST" action={AppendUrl(customer.Id)}>
              <table>
                <tr>
                  {customer.Name}{" "}
                  <input
                    type="submit"
                    value="Select"
                    id="select-button-customer"
                  />
                </tr>
              </table>
            </form>
          ))
        ) : (
          <h1>No results found!</h1>
        )}
      </ul>
      </div>
    </div>
  );
};

export default FindCustomer;

CodePudding user response:

I would create two separate fetching functions. Also watch out for confusing async await with then(). A simple example:

export async function getStartData() {
  const partnerRes = await fetch(url, options)
  const data = await partnerRes.json()
  loadDetails(data)
}

async function loadDetails(data) {
  for(let partner of data) {
     let result = await fetch(`someurl?id=${partner.id}`, options)
     let partnerdata = result.json()
     console.log(partnerdata) // or whatever you need to do    
  }
}

CodePudding user response:

I don't understand what your exact problem is. but you can follow this.

 export async function getStaticProps() {
  try {
    const partnerRes = await fetch(
      `${process.env.REACT_APP_REQUESTURI}/api/Partners`,
      {
        headers: {
          Authorization: "Bearer "   process.env.REACT_APP_ACCESS_TOKEN,
          "Content-Type": "application/json",
        },
      }
    )
    const partner = partnerRes.json();
    
    if(partner.id) {
      // if you want to iterate partnerRes, then run iternation, after that call customerres
      const customerRes = await  fetch(
        `${process.env.REACT_APP_REQUESTURI}/api/Partners/${partner.Id}/Customers`,
        {
          headers: {
            Authorization: "Bearer "   process.env.REACT_APP_ACCESS_TOKEN,
            "Content-Type": "application/json",
          },
        }
      );
      return {
        props: {
            customerRes: customerRes,
        },
    }
    }
  } catch (error) {
    return {
        props: {
          customerRes: {}, // handle error
        },
    }
  }
}
  • Related