Home > Enterprise >  How to Make A second API call based on the value gotten from the first. with React and useEffect hoo
How to Make A second API call based on the value gotten from the first. with React and useEffect hoo

Time:01-08

Im trying to make a call to the first APi that contains a payload of different CATEGORIES and then use that to make a second call to another API that contains different category items from each CATEGORY from the first. I am new to react and don't quite know how to make the logic work. This is my idea below. Category items are displayed based on the selected CATEGORIES. I am confused on how to use the value from the first to make the second call.

const [catalog,setCatalog] = useState([]);
const [catalogItems,setCatalogItems]= useState([]);

useEffect(() => {

    const fetchData = async () => {

      await fetchMarketingCategories()

     .then((result)=>{

        setCatalog(result);

          console.log("result",result);
         
     })

     .then(async (categoryId)=>{
         
          const {items = []} = await getAdvisorMarketingCatalog(categoryId)

          setCatalogItems(items);
     })
     

    };
    fetchData();

    
    });
  }, []);

CodePudding user response:

just use async await, don't use async await with "then".

Just like this.

useEffect(async () => {
  const result = await fetchMarketingCategories()

  setCatalog(result)

  console.log('result', result)

  // not sure how you want to get the id from result
  const categoryId = getCategoryIdFromResult(result)

  const { items = [] } = await getAdvisorMarketingCatalog(categoryId)

  setCatalogItems(items)
})

CodePudding user response:

Not completely sure what you what, but I will explain what am I doing below.

When my component loads, with the help of my first useEffect hook am fetching the first catalogs. These results are then rendered in the UI. When user clicks on any of the catalog am setting its id in state and with the help of my second useEffect am fetching the next result from api

Here is my code

function App() {
  const [catalog, setCatalog] = useState([]);
  const [catalogItems, setCatalogItems] = useState([]);
  const [selectedCatalog, setSelectedCatalog] = useState();

  useEffect(() => {
    const fetchData = async () => {
      const result = await fetchMarketingCategories();
      setCatalog(result);
      console.log("result", result);
    };
    fetchData();
  }, []);

  useEffect(() => {
    const fetchDetails = async () => {
      const { items = [] } = await getAdvisorMarketingCatalog(selectedCatalog);
      setCatalogItems(items);
    };
    if (selectedCatalog) {
      fetchDetails();
    }
  }, [selectedCatalog]);

  return (
    <div>
      {catalog?.map((c) => (
        <div onClick={() => setSelectedCatalog(c.id)}>{c.name}</div>
      ))}
    </div>
  );
}
  •  Tags:  
  • Related