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

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

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 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