Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda