Tengo una duda sobre React. tengo dos funciones en
import { useState, useEffect } from 'react' import './transactions.css' function TransactionHistory () { const [last_account_id, setAccountId] = useState(); const http_request = async url => { try { const response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }); if (response.status === 200) { return [true, response]; } } catch (error) { console.log(error); return [false, null]; } } const get_transactions = async () => { let transactions_promise = new Promise((resolve, reject) => { let transactions = http_request('http://127.0.0.1:8000/transactions'); resolve(transactions); }); let transactions_response = await transactions_promise; } const get_account_details = async () => { let url = 'http://127.0.0.1:8000/accounts/' + last_account_id; let account_promise = new Promise((resolve, reject) => { let account = http_request(url) resolve(account) }) let account_response = await account_promise } const run_apis = async () => { await get_transactions(); await get_account_details(); } useEffect(() => { run_apis() }, [last_account_id]) return () } export default TransactionHistoryRecibo una solicitud incorrecta inicialmente de get_account_details() y mis casos de prueba están fallando. Pero funciona después. El useState last_account_id no está definido inicialmente y eso está causando la solicitud incorrecta.
Por favor, ayúdame a encontrar una solución.
La clave para comprender esta pregunta proviene de un comentario sobre otra respuesta, citado aquí:
El error de solicitud incorrecta proviene de funct2() debido a un estado de uso no definido en funct1()
Entonces estás activando funct2 en respuesta a algo incorrecto. Si necesita que se ejecute cuando se define un estado, debe hacer que se ejecute en respuesta al cambio de estado colocándolo en su propio gancho de efecto.
const [someState, setSomeState] = useState(null); useEffect(() => { func1(); }, []); // Note the addition of the dependency array so that this only runs when the component is initially mounted useEffect(() => { if (someState === null) return; // Don't run funct2 if the state hasn't been set yet funct2(); }, [someState]); // Note that we run this function whenever the state is changed Alternativamente, podría hacer que funct1 devuelva el valor (posiblemente a través de una promesa de await ), luego pase ese valor a funct2 y luego lea el valor de los argumentos en lugar del estado (porque el valor anterior del estado se habría cerrado en ese punto).
Puedes esperar a que termine la función con await
const executeFns = async () => { await funct1(); await funct2(); }; // Then in your effect you can call your "executeFns" useEffect(() => { executeFns(); }, []);