Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

282
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda