1

I am hoping somebody can help me with what I'm trying to do.

So I'm fetching an API endpoint that returns sets of data which is fine, but what What I like to do is to use all campaignid parameter values and make an api call one-by-one to retrieve each campaignid value's results so it would use each id from the campaignid and makes an api call, obviously the end point for the other call would be different. Just wondering how do I do that dynamically

import { useState, useEffect } from "react";

const url = "https://6271dd6bc455a64564b8b6b6.mockapi.io/AP1/REST/Numberofsubmissons";

export default function App() {
  const [data, setData] = useState([]);
  console.log(data);

  useEffect(() => {
 
      fetch(url)
        .then((response) => response.json())
        .then((data) => setData(data))
      
  }, []);

  return (
    <>
   
      <code>{JSON.stringify(data)}</code>
    </>
  );
}
7
  • So the code calls fetch(url) and this returns what exactly? Is your question how to then take this data value and make a bunch of new requests? Can you edit to include a minimal reproducible example for what you are trying to do? What are the subsequent API requests you want to make? Commented Nov 16, 2022 at 1:09
  • @DrewReese here's the sandbox i created codesandbox.io/s/react-fetch-onclick-forked-y9j5ox?file=/src/… Based on what is retrieved, use the campaignid value in a separate section on my code to do an api call directly to that unique id to retrieve. Basically, the end point would be like XXXX.com/campaignidvalue I just dont know how to do that. It should also go through each campaignid one by one like a loop and return the results Commented Nov 16, 2022 at 1:20
  • We can already see what that initial response is. What are you trying to use from it for the next batch of requests? Commented Nov 16, 2022 at 1:25
  • @DrewReese so taking what is retrieved, and making api calls in a different section using useeffects XXXX.com/campaignidvalue1 XXXX.com/campaignidvalue2 XXXX.com/campaignidvalue3 Commented Nov 16, 2022 at 1:26
  • @DrewReese correct use the first response, and make api calls one by one based on each campaignid Commented Nov 16, 2022 at 1:27

2 Answers 2

2

You could add an extra useEffect that listens to data changes and then, based on the campaignid make several calls to the different API with that campaignid.

useEffect(() => {
   if (Array.isArray(data)) {
      Promise.all(
        data.map(async ({ campaignid }) => {
          const response = await fetch(`${url}/${campaignid}`);
          return await response.json();
        }),
      ).then((res) => { setNewData(res) });
    }
}, [data]);

Made some playable code, using some fake promises - the response can be stored as an object with { [campaignid]: data } structure or something similar depends on your needs.

Codesandbox: https://codesandbox.io/s/react-fetch-onclick-forked-o1q36b?file=/src/App.js

Sign up to request clarification or add additional context in comments.

Comments

2

The first API request returns an array of data that contains campaignid values. You can map this fetched data array to an array of fetch Promises fetching the campaign data by id. The resolved array will have all the fetched data that you can save also into local state.

const baseUrl = "https://6271dd6bc455a64564b8b6b6.mockapi.io/AP1/REST/";

export default function App() {
  const [data, setData] = useState([]);
  const [campaignData, setCampaignData] = useState([]);

  useEffect(() => {
    const fetchAllData = async () => {
      try {
        const response = await fetch(baseUrl + "Numberofsubmissons");
        const data = await response.json();

        setData(data); // save data to state

        const campaignDataReqs = data.map(async ({ campaignid }) => {
          const response = await fetch(baseUrl + `campaigndetails/${campaignid}`);
          const campaignData = await response.json();
          return campaignData;
        });

        const campaignData = await Promise.all(campaignDataReqs);

        setCampaignData(campaignData); // save campaign data to state
      } catch(error) {
        // catch and handle any rejected Promises or thrown errors
      }
    };

    fetchAllData();
  }, []);

  return (
    ....
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.