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

208
Vistas
useState() is not overwriting data properly

I am running a Flask backend and a React frontend. Depending on some options on the frontend, data is fetched from the backend and returned to the frontend. One thing that happens is that when the page is loading there is a default state, which returns some data from the beginning.

One of the things that is returned are 5 arrays with length 24. I can see from the backend what they look like, and there are no problems. Then if I switch the default state (resulting in different data returned) the backend should instead return 5 arrays with length 48 instead of 24, i.e. same type of object but with different lengths.

However, this is there it stops working. When I go from 48 to 24 in length, there are no issues, but when I go from 24 to 48 it stops, and I receive a Uncaught TypeError: Cannot read properties of undefined (reading '1') error. I can see in the backend that it returns 5 arrays of length 48, but on the frontend, if I do a console log of the length of the arrays, the first array is length 48, but the next 4 is only 24. So it seems like there are some issues with updating the state of the data in the frontend.

I fetch my data by:

function fetchData(e) {
        e?.preventDefault();
        POST('/api', { data1: data1, data2: data2, data3: data3, data4: data4, data5: data5 }).then(
            async (response) => {
                const json = await response.json()
                setData1(json.data1)
                setData2(json.data2)
                setData3(json.data3)
                setData4(json.data4)
                setData5(json.data5)
            }
        )
    }

Where the useStates are defined as:

const [data1, setData1] = useState([]);
const [data2, setData2] = useState([]);
const [data3, setData3] = useState([]);
const [data4, setData4] = useState([]);
const [data5, setData5] = useState([]);

So can anyone maybe spot what I might be doing wrong ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Maybe if you use await in each setstate you will have a better result, is not the best practice, but should do the work:

function fetchData(e) {
        e?.preventDefault();
        POST('/api', { data1: data1, data2: data2, data3: data3, data4: data4, data5: data5 }).then(
            async (response) => {
                const json = await response.json()
                await setData1(json.data1)
                await setData2(json.data2)
                await setData3(json.data3)
                await setData4(json.data4)
                await setData5(json.data5)
            }
        )
    }

Edit 1

Based on comments, you should change the data structure as follows:

function fetchData(e) {
        e?.preventDefault();
        POST('/api', data).then(
            async (response) => {
                const json = await response.json()
                setData(json)
            }
        )
    }

You still have all data and you will access to it with data.data1. As you can see to make the call to the API you just need the data object and you don't need to destructure it.

about 4 years ago · Juan Pablo Isaza Denunciar

0

The first i can think of is that:

setCount(count + 1);
setCount((prevCount) => prevCount + 1)

In the first line we are updating the state, but we are not sure when its going to be updated, on the other hand on the second line we use the callback that the setter provides, and thats how we are sure thah we are going to get the updated value.

So, useState() is asynchronous, there is no confirmation of that the data is going to be updated by the order you put it in your code. And that is the issue here.

For in depth explanation, take a look at the refs:
https://reactjs.org/docs/hooks-state.html
Why is setState in reactjs Async instead of Sync?

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