Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
Agregar a useState<Array> dentro de useEffect dentro de una promesa

En teoría, la matriz debe completarse continuamente y debe reflejarse en la representación de la página, pero en lugar de eso, se sobrescribe. terminando con una lista que tiene solo el último valor agregado.
Esta es una versión reducida de lo que estoy tratando de obtener.

 // Just a function to simulate fetching data from an API async function getData(id) { // Simulate Delay await new Promise((r) => setTimeout(r, id * 1000)); return `Data ${id}`; } function App(props) { const [data, setData] = React.useState("Loading..."); const [arr, setArr] = React.useState([]); React.useEffect(() => { getData(0).then(setData); }, []); React.useEffect(() => { if (data && arr.length == 0) { for (let i = 1; i < 6; i++) { getData(i).then((resolve) => { setArr([resolve, ...arr]); }); } } else { setArr([]); } }, [data]); return ( <> <h3>{data}</h3> <ul> {arr.map((item) => ( <li key={item}>{item}</li> ))} </ul> </> ); }

Esperado

Datos 0

  • Datos 1
  • Datos 2
  • Datos 3
  • Datos 4
  • Datos 5

En cambio

Datos 0

  • Datos 5
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Después de investigar, descubrí que podía pasar una función a setState() en forma de (currentStateValue) => {} . Para evitar que los datos se llamen dos veces debido a que el segundo useEffect se activa dos veces, cree otro estado isFetchingMoreData para verificar.

 // Just a function to simulate fetching data from an API async function getData(id) { // Simulate Delay await new Promise((r) => setTimeout(r, id * 1000)); return `Data ${id}`; } function App(props) { const [data, setData] = React.useState("Loading..."); const [arr, setArr] = React.useState([]); const [isFecthingMoreData, setIsFecthingMoreData] = React.useState(false); React.useEffect(() => { getData(0).then(setData); setIsFecthingMoreData(true); }, []); React.useEffect(() => { if (isFecthingMoreData) { setIsFecthingMoreData(false); for (let i = 1; i < 6; i++) getData(i).then((resolve) => { setArr((prev )=>[...prev, resolve]); }); } else { setArr([]); } }, [data]); return ( <> <h3>{data}</h3> <ul> {arr.map((item) => ( <li key={item}>{item}</li> ))} </ul> </> ); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!