Hello! I just made this component and I was wondering how would you split it? or what would you do differently ?
https://gitlab.com/Saphyel/imperialarch/-/blob/master/src/App.tsx?ref_type=heads
I'm mostly interested in this file, so you can ignore the rest
#TypeScript + React
10 messages · Page 1 of 1 (latest)
doing all that in useEffect is wild
where would be the best place?
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
what would be the right place forthis new module? services/database.ts ?
I pushed a refactor of the logic of the DB to another module so now the useEffect is cleaner 👍🏻 thanks! any other thing??
That's the primary thing that jumped out at me
could you check for other improvements please ? 🥹 