Home > database >  Fetch API dynamically using react from a property
Fetch API dynamically using react from a property

Time:11-16

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

CodePudding user response:

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

CodePudding user response:

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

  • Related