How can I write a promise with async and await methods?

<%= @topic_view.topic.title %>
<%= @topic_view.topic.average_rating %> <%= @topic_view.topic.posts.count { |p| !!p.custom_fields['rating'] } %>

Here is the method I want to change

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));
}

And here I use this

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);
            }
        });
    }
}

Try just console.logging data without condition, just after getting it. I.e just after

.then(data =>{
console.log(data);
if(..)){
...

to see if it’s exists or is it in wanted format …

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:

export const getProducts = async (sortBy) => {
  const resp = await fetch(`${API}/products?sortBy=${sortBy}&order=desc&limit=6`);
  if (resp.status < 200 || resp.status > 299) {
    throw new Error(`Network error, ${resp.status} status.`);
  }
  return resp.json();
});
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 :crossed_fingers::crossed_fingers::crossed_fingers::crossed_fingers:] the next month or so.