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

280
Views
useState (setState) no configura los elementos de la matriz según lo previsto

Mi objetivo es tomar la información de tempArr y establecerla como postData . Si no uso la declaración if, sigue recorriendo todos los datos de la matriz mencionada anteriormente. Si bien tempArr contiene toda la información necesaria de la base de datos, creo que el problema radica en el gancho useEffect porque, según tengo entendido, simplemente no se repite la segunda vez. Lamentablemente no tengo idea de cómo solucionarlo. Se proporciona una imagen de la consola para comprender mejor el problema.

 const [postData, setPost] = useState([]) const axios = require('axios'); let done = false; let tempArr = [] useEffect(() => { axiosPull() console.log(done, "before the if statement") if(done){ console.log("inside the IF statement") {setPost(tempArr)} done = false } }) const axiosPull = () => { const url = 'http://localhost/.../api/product/bookRead' const url2 = 'http://localhost/.../api/product/furnitureRead' const url3 = 'http://localhost/.../api/product/dvdRead' axios.get(url).then(response => response.data) .then((data) => { data.data.map(data =>{ tempArr.push(data) }) }) axios.get(url2).then(response => response.data) .then((data) => { data.data.map(data =>{ tempArr.push(data) }) }) axios.get(url3).then(response => response.data) .then((data) => { data.data.map(data =>{ tempArr.push(data) }) console.log(tempArr) done = true console.log(done) }) }; return ( <div> <div className="productContainer"> <Post posts={postData} /> </div> </div> )

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

0

Probablemente debería tener una matriz de dependencias vacía en ese useEffect para evitar que se ejecute en cada procesamiento.

 useEffect(() => { axiosPull(); }, []);

Puede a) acortar su código, b) eliminar la dependencia de una variable de componente local ( tmpArr ) y c) establecer el estado dentro de la función axiosPull en sí.

 function axiosPull() { const url = 'http://localhost/.../api/product/bookRead' const url2 = 'http://localhost/.../api/product/furnitureRead' const url3 = 'http://localhost/.../api/product/dvdRead'; // Group the urls in an array const urls = [url1, url2, url3]; // Create an array of promises const promises = urls.map(url => { return axios.get(url); }); // Wait til they either resolve/reject Promise.all(promises).then(responses => { // Then `map` over the responses of each // resolved promise and return the data you were // adding to `tempArr`. You may need `flatMap` here // instead of `map` depending on your use-case const mapped = responses.map(data => { return data.data; }); // And then set the state with that data setPost(mapped); }); };
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!