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

152
Vistas
.push( ) is not updating the variable

I am trying to push the data that is set using setData function to datas[ ]. I am able to push the data once, but the 2nd time when I push it, instead of being stored at datas[1], it replaces datas[0]. What am I doing wrong here. Thank you in advance.

export default function App() {
 const [data,setData]= useState([]);
 const [activity, setActivity]= useState([])
 const [name, setName] = useState("")

 const datas=[];
 useEffect(()=>{
  // handlePress()
 }, [setData, setName])

 const rand= Math.floor(Math.random(1,5)*4)+1
 const events=["Event A","Event B","Event C","Event D","Event E"]

 const handlePress=(day)=>{
   setData(day);
   setName(`${events[rand]}`)
   datas.push(data);
   console.log(datas);
 }
  return (
    <div className="App">
      <Calendar 
        onDayPress={day => {
          {handlePress(day)}
        }}
        
      />
      
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

the datas array is added inside the component. Everytime the component re-renders, it is re-initialized to empty array.

Also, on onDayPress prop in the callback function you've added an extra pair of curly brackets

about 4 years ago · Juan Pablo Isaza Denunciar

0

App is getting re-rendered whenever you change states, so const datas=[]; will be initialized as a new array.

One more problem I can foresee is that you call setData(day) and then call datas.push(data) on the same function which won't be applied with your latest data because states' changes are asynchronous

const handlePress=(day)=>{
   setData(day); //`day` is set here but not applied immediately
   setName(`${events[rand]}`)
   datas.push(data); //data is the previous data, not `day`
   console.log(datas);
 }

The full modification can be

const datas=[]; //move your `datas` to the global scope

export default function App() {
 const [data,setData]= useState([]);
 const [activity, setActivity]= useState([])
 const [name, setName] = useState("")

 
 useEffect(()=>{
  // handlePress()
 }, [setData, setName])

 const rand= Math.floor(Math.random(1,5)*4)+1
 const events=["Event A","Event B","Event C","Event D","Event E"]

 const handlePress=(day)=>{
   setData(day); //`data` will be changed later
   setName(`${events[rand]}`)
   datas.push(day); //push `day` directly instead of data
   console.log(datas);
 }
  return (
    <div className="App">
      <Calendar 
        onDayPress={day => {
          {handlePress(day)}
        }}
        
      />
      
    </div>
  );
}

You also should not use useEffect with setters (setData and setName). These setters have nothing to do with side-effects. You should pass state values as dependencies in useEffect.

//whenever `name` or `data` change, `useEffect` will be triggered
useEffect(()=>{
  //TODO: Do your logic here
 }, [data, name])
about 4 years ago · Juan Pablo Isaza Denunciar

0

In react when you update the state , react component is re-rendered . So here when you update state in handlePress() function your component is re-rendered .So your datas array is re-intialized and become empty again . So every time when you push item it will add to 1st position. Hope it will help you.

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