You can’t do what you’re trying to do here. useEffect is the missing piece, as it’s the thing that allows side effects; I’ll convert it async await as well:
const Home = () => {
const [productsByArrival, setProductsByArrival] = React.useState([]);
const [error, setError] = React.useState(null);
React.useEffect(() => {
const loadProductByArrival = async () => {
try {
const data = await getProducts("createdAt");
setProductsByArrival(data);
} catch(err) {
setError(err);
}
};
loadProductByArrival();
}, []);
// NOTE the second argument, the array of
// dependencies. An empty array means this effect will
// run once, when the component loads.
// The array is _really_ important.
return /* your UI here */
}
useEffect is super duper important if you’re learning hooks and you need to fetch data. It has a lot of subtleties, and it can be difficult to grok at first, but you need to know how to use it.
NOTE: hooks are not really designed for fetching data. useEffect has to do at the minute, and is works fine. But there is a thing called “suspense for data loading” which will land in React in [hopefully, hopefully, hopefully ] the next month or so.