Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
How to Make A second API call based on the value gotten from the first. with React and useEffect hooks

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

    
    });
  }, []);
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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)
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

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, I am fetching the first catalogs. These results are then rendered in the UI. When the user clicks on any of the catalogs I am setting its id in state and, with the help of my second useEffect, I 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>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think you are trying to fetch data based on previously fetched data and do it simultaneously. To do so one way can be:

const fetchData = async () => {
 try {
  const getCategories = await fetchMarketingCategories()
  setCatalog(getCategories)

  // Now if fetch1 gives you array of catalogs with id you can just use 
  // Array.map() to fetch catalog items. But this will ping a lot of request 
  // to the api. But if this is the only way you need to do then go ahead.
 
  let finalData = []
  finalData = getCategories.map(async (items, idx)=> {
   return await getAdvisorMarketingCatalog(items.id)
  })
  setCatalogItems(finalData)
 } catch (err) {
    // Do what you want with the error
 }
}
useEffect(()=> {
 let ignore = false
 
 if (!ignore) {
  fetchData()
 }
 
 return () => ignore = true
}, [])
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda