It happens to me that the page crashes because it does not have time to receive the promise, that is, when I reload it the error disappears but I want to avoid it appearing the first time I load the page to achieve this I want to use asyn and await .
import React, { useState, useEffect } from 'react';
import { getProducts } from './apiCore';
const Home = () => {
const [productsByArrival, setProductsByArrival] = useState([]);
const loadProductByArrival = () => {
getProducts("createdAt").then(data => {
if(data.error) {
setError(data.error);
} else {
setProductsByArrival(data);
}
});
}
}
Here I show the getProducts method and I would like to know how to convert it into a promise with await and async .
export const getProducts = (sortBy) => {
return fetch(`${API}/products?sortBy=${sortBy}&order=desc&limit=6`, {
method: "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
}
Using
catch
in services can become a bad idea if you don't rethrow or transform the exception because the service consumer can't tell if an error occurred or not.Change your service to this:
You could also completely remove the one
catch
from the service. I personally prefer it this way because errors almost always require visual feedback from the user.As a last alternative you can return an object with a couple of properties like
error
ordata
but this would complicate your ability to control the flow of errors a bit by removing the error channel from the promise chain.Then in your component:
Translated to
async
andawait
Your pattern to convert to async-await would look like:
Y
your call to Home is not altered. On the other hand, so that your result doesn't crash, what you have to do is initialize your component with an ad hoc message (on purpose), so that it doesn't present anything while it loads. and as soon as you receive the data, update the state.