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

273
Visualizações
Array being filled in inverse in React

I am trying to fill an array with several array of objects, but on first render, the values are being filled in inverse inside the array and after refreshing they go back to how they should be.


  const getProducts = async (data) => {
    await productServices
      .getProductsByTakeoffWizardStep(data)
      .then((response) => {
        setRows((rows) => [...rows, response.data]);
      })
      .catch((error) => {
        console.log(error.response);
      });
  };

  const getTakeoffIDs = () => {
    var i = 1;
    takeoffServices
      .getTakeoffSteps(5)
      .then((response) => {

        response.data.forEach((element) => {
          setSteps((steps) => [...steps, element.description]);
          setStepsID((stepsID) => [...stepsID, element.stepID]);
          var data = { StepID: element.stepID, TakeoffID: 4 };
          getProducts(data);
          setStepSequence((stepSequence) => [
            ...stepSequence,
            "Step " + i + "",
          ]);
          i = i + 1;
        });
      })
      .catch((error) => {
        console.log(error.response);
      });
  };

  useEffect(() => {
    setSteps([]);
    setStepsID([]);
    setRows([]);
    getTakeoffIDs();
  }, []);

So on first render the array looks like this

(2) [Array(1), Array(2)]
0: Array(1)
0: {product: {…}, quantity: null}
length: 1
[[Prototype]]: Array(0)
1: Array(2)
0: {product: {…}, quantity: null}
1: {product: {…}, quantity: null}
length: 2
[[Prototype]]: Array(0)
length: 2
[[Prototype]]: Array(0)

and after refreshing the page it looks like this

(2) [Array(2), Array(1)]
0: Array(2)
0: {product: {…}, quantity: null}
1: {product: {…}, quantity: null}
length: 2
[[Prototype]]: Array(0)
1: Array(1)
0: {product: {…}, quantity: null}
length: 1
[[Prototype]]: Array(0)
length: 2
[[Prototype]]: Array(0)

What could be causing this and what can I do to fix it?

I am accessing the page using history.push() from another page but none of the states I am passing affects the fetching process, only the display of some paragraphs not related to the data I am fetching.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is how I would write this:

const getProduct = async (data) => {
  try {
    const response = await productServices.getProductsByTakeoffWizardStep(data);
    return response.data;
  } catch (error) {
    console.log(error.response);
  }
}

const getTakeoffIDs = () => {
  takeoffServices
    .getTakeoffSteps(5)
    .then(async (response) => {

      // try moving setSteps(), setStepsID() and setStepSequence() up here, so they don't wait for the products.

      const products = await Promise.all(
        response.data.map(element => getProduct({
          StepID: element.stepID,
          TakeoffID: 4
        }))
      );

      setRows((rows) => [
        ...rows,
        ...products
      ]);
      setSteps((steps) => [
        ...steps,
        ...response.data.map(element => element.description)
      ]);
      setStepsID((stepsID) => [
        ...stepsID,
        ...response.data.map(element => element.stepID)
      ]);
      setStepSequence((stepSequence) => [
        ...stepSequence,
        ...response.data((_, i) => `Step ${i + 1}`)
      ]);
    })
    .catch((error) => {
      console.log(error.response);
    });
};


useEffect(() => {
  setSteps([]);
  setStepsID([]);
  setRows([]);
  getTakeoffIDs();
}, []);
  • Instead of calling all these setState()s multiple times I'd Array.map() the data and add it all at once.
  • await for all the getProduct() calls to finish and also push them at once; in order.

The one thing I'm not sure about is if you want the setRows() to be called together with the other setter, or if the other ones should go first (because the data is available) and setRows() should be called later, as soon as the data is available.

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