#TypeScript + React

10 messages · Page 1 of 1 (latest)

glass heart
wintry meadow
#

doing all that in useEffect is wild

glass heart
wintry meadow
#

Generally you would want to extract things outside of the useeffect to islote more logic if you can from the appearance

#

let db: null | SQL.Database = null; // Whatever the correct type is

const getDB = async () => {
  if (db) {
    return db
  }

  const SQL = await initSqlJs({
    locateFile: (file: string) => `https://sql.js.org/dist/${file}`
  });


  const response = await fetch('/data/datos.sqlite');
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

  const buffer = await response.arrayBuffer();
  const db = new SQL.Database(new Uint8Array(buffer));

  return db
}

async function fetchItems(db) {
  const result = db.exec(
      "SELECT fecha, pais_origen, pais_objetivo, descripcion, enlace_url FROM intervenciones ORDER BY fecha"
  )[0];
  // if result is not ok { return [] or throw error? }

  return result.values.map(([
    fecha,
    paisOrigen,
    paisObjetivo,
    descripcion,
    enlaceUrl
  ]: [string, string, string, string, string]) => ({
    title: formatDateToYMD(fecha),
    cardTitle: `${paisOrigen} to ${paisObjetivo}`,
    cardSubtitle: `${enlaceUrl}`,
    cardDetailedText: `${descripcion || ""}`
  }));
}

function App() {
  const [items, setItems] = useState<TimelineItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadData = async () => {
      try {
        const db = await getDB()
        setItems(await fetchItems(db));
      } catch (err) {
        setError(`Error cargando datos: ${err instanceof Error ? err.message : 'Error desconocido'}`);
        console.error('Error loading SQLite data:', err);
      } finally {
        setLoading(false);
      }
    };

    loadData();

    return async () => { // handle unmounting
      const db = await getDB()
      db.close()
    }
  }, []);
  // rest of code
#

You can then move all the DB interactions to a new module

glass heart
glass heart
#

I pushed a refactor of the logic of the DB to another module so now the useEffect is cleaner 👍🏻 thanks! any other thing??

wintry meadow
#

That's the primary thing that jumped out at me

glass heart