Problems consuming api - React

Asked

Viewed 40 times

0

I am consuming an api that returns an array of products with Axios, but it returns a Promise, and I cannot use it in my component, because at the time the component renders, the Promise is still not solved!

function pegaDados() {
  return new Promise((resolve, reject) => {
    resolve( axios.get('https://cd8wxyy7ba.execute-api.sa-east-1.amazonaws.com/dev/products'))
  })
  
}

const dados = pegaDados().then( data => { return data.data})
console.log(dados)

When I try to make a data.map(...) to go through this array, I cannot because . map is not a data function

  • It is because it is usually not possible to return data from within a then, what you can do is to place this chunk within an async function and return with await: type:function teste async () { const dados = await pegaDados();

  • É porque geralmente não se é possível retornar dados de dentro de um then wrong statement!

1 answer

1


Your code has one Promise who has another Promise within a function resolve of the first Promise, and none of this is necessary, because, the axios already returns a Promise and can be solved easily:

async function pegaDados() {
    try {
        return await axios
            .get('https://cd8wxyy7ba.execute-api.sa-east-1.amazonaws.com/dev/products');
    } catch (e) {
        console.log(e);
    }    
}

is one of the forms of solution with async/await where this function returns the information of this API or an error where it can be checked.

Functional example with using then, because here on the site does not work unfortunately async/await, but, nothing prevents use, example:

function App() {
  const [data, setData] = React.useState([]);
  const loadData = () => {
    axios.get('https://cd8wxyy7ba.execute-api.sa-east-1.amazonaws.com/dev/products')
    .then(result => setData(result.data));
  }
  React.useEffect(() => {
    loadData();
  }, []);
  if (data.length === 0) {
    return <div>Carregando ...</div>;
  }
  return (
    <React.Fragment>
    {data.map(item => (
      <div>
        {item.productSku} - {item.productDescription}
      </div>
    ))}
    </React.Fragment>
  )
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div id="root"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.