Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
useState (setState) not setting array items as intended

My goal is to take the information from tempArr and set it as postData. If I don't use the if statement it keeps looping through all the data from the before mentioned array. While the tempArr contains all the necessary information from DB, I think that the problem lies in the useEffect hook because as far as I understand it just doesn't loop through it the second time. Sadly I have no idea how to fix it. A picture from console is provided to better understand the problem.

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 Respuestas
Responde la pregunta

0

You should probably have an empty dependency array in that useEffect to prevent it running on each render.

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

You can a) shorten your code, b) remove the dependence of a local component variable (tmpArr), and c) set state within the axiosPull function itself.

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda