Visual Studio Code sugiere refactorizar el código para reducir la complejidad. No sé qué es Promise y cómo refactorizar el código a continuación. ¿Alguien puede ayudarme?
const handleLoadInventory = async () => { try { const _data = await fetch('http://localhost:4000/api/v1/inventory/', { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + localStorage.getItem('token'), }, }) if (_data.status === 200) { const data = await _data.json() if (data.items.length !== 0) { if (inventoryData.length) for (let i = 1; i <= Math.ceil(data.items.length / 10); i++) { pagination.push(i) } for (let i = 0; i < 10 && i < data.items.length; i++) { showData.push(data.items[i]) } setInventoryData(data.items) } else { setZeroAlert(true) } } else { setServerAlert(true) throw new Error() } } catch (err) { setServerAlert(true) console.error(err) } }La refactorización es el arte de dividir funciones en unidades más pequeñas. La idea clave detrás de esto es hacer que una función sea "obvia" haciéndola pequeña para que los errores también se vuelvan obvios. Realmente no necesitas saber nada más que cómo funcionan las funciones.
La primera parte que extraería es la fetch porque probablemente la usarás más de una vez. Copiar/pegar el código de recuperación que tiene es propenso a errores. Puede olvidar establecer su tipo de contenido o puede olvidar incluir el token de autenticación.
Por lo tanto, merece convertirse en su propia función, no solo en una pieza de código:
// This function returns a promise because fetch returns a promise: function get (url) { return fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + localStorage.getItem('token'), }, }) } Lo siguiente es el manejo del código de estado 200. Está utilizando un bloque if . Eso significa asegurarse de que todas las funciones que obtienen datos tengan la misma estructura. Nuevamente, es propenso a errores debido a la programación de copiar/pegar.
Dado que está configurando un estado y arrojando un error de todos modos, puede manejarlo en la función get() anterior:
// This function returns a promise because fetch returns a promise: async function get (url) { let response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + localStorage.getItem('token'), }, }) if (response.status !== 200) { throw new Error('Server response invalid') } return response } setServerAlert() será manejado por su bloque externo try/catch ya que estamos arrojando un error.
Ahora su código se simplifica considerablemente:
const handleLoadInventory = async () => { try { const _data = await get('http://localhost:4000/api/v1/inventory/') const data = await _data.json() if (data.items.length !== 0) { if (inventoryData.length) for (let i = 1; i <= Math.ceil(data.items.length / 10); i++) { pagination.push(i) } for (let i = 0; i < 10 && i < data.items.length; i++) { showData.push(data.items[i]) } setInventoryData(data.items) } else { setZeroAlert(true) } } catch (err) { setServerAlert(true) console.error(err) } } Personalmente, incluso movería la parte _data.json() a la función get() , pero creo que entiendes el punto.