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

176
Vistas
React Fetch not working for one link but works for another

I am trying to use react to fetch api information (see below) but it is not returning any values but works when I use a different link. Not sure what the issue is with the second link. How do I make the second link work or is there a different method?

import React, { useState, useEffect } from "react";
import axios from "axios";
export default function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    getData()
}, []);

async function getData() {
  // await axios("https://randomuser.me/api")             // <----- this works
  await axios("https://api.sampleapis.com/wines/reds")    // <----- this does not work
  .then((response) => {
    setData(response.data);
    console.error("No Error fetching data: fds");
  })
  .catch((error) => {
    console.error("Error fetching data: ", error);
    setError(error);
  })
  .finally(() => {
    setLoading(false);
  });
}
if (loading) return "Loading...";
if (error) return "Error!"; //dfdsaf
return ( <>
    {/* <img src={data.results[0].picture.medium} alt="random user" /> */}
    <pre>{JSON.stringify(data, null, 2)}</pre>
  </>
); }

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The structures of the returning data from each APIs are different from each other.

https://randomuser.me/api -> returns {"results":[{"gender"...

https://api.sampleapis.com/wines/reds -> returns [{"winery":"Maselva","wine"...

So obviously just changing the URL won't work. You have to change the code accordingly to the structure of the returned data to access them properly.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The response structure is different and you may not need to use .then and .catch as you have already used Async/Await.

Here's a working example in codesandbox

<script type="text/babel">
// import React, { useState, useEffect } from "react";
// import axios from "axios";
const { useState, useEffect } = React;

function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [randomUserData, setRandomUserData] = useState(null);
  const [randomUserLoading, setRandomUserLoading] = useState(true);
  const [randomUserError, setRandomUserError] = useState(null);
  useEffect(() => {
    getRandomUserData();
    getSampleApiData();
  }, []);

  async function getSampleApiData() {
    try {
      const response = await axios("https://api.sampleapis.com/wines/reds");
      setData(response.data);
      console.error("No Error fetching data: fds");
    } catch (error) {
      console.error("Error fetching data: ", error);
      setError(error);
    }
    setLoading(false);
  }

  async function getRandomUserData() {
    try {
      const response = await axios("https://randomuser.me/api");
      setRandomUserData(response.data);
      console.error("No Error fetching data: fds");
    } catch (error) {
      console.error("Error fetching data: ", error);
      setRandomUserError(error);
    }
    setRandomUserLoading(false);
  }

  if (loading || randomUserLoading) return "Loading...";
  if (error || randomUserError) return "Error!";
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(2, 1fr)",
        width: "100%"
      }}
    >
      <div>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>
      <div>
        <pre>{JSON.stringify(randomUserData, null, 2)}</pre>
      </div>
    </div>
  );
}

// export default App;
ReactDOM.render(<App />, document.querySelector("#app"));
</script>

<div id="app"></div>

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/axios@0/dist/axios.js"></script>
<script crossorigin src="https://unpkg.com/@babel/standalone@7/babel.js"></script>

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