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

181
Vistas
How can I pass a value into a useState

I am new to learning js and react. I have created a RNG function that works on its own. However, I would like to pass its value into my ticketNumber variable in my useState. I have attempted various methods of passing the value in by "tickeNumber = rng, and even attempted to do it by doing "setComplaints(...complaint, ticketNumber = Math.floor(Math.random() * (maxValue - minValue + 1) + minValue));

const [complaint, setComplaints] = useState({
    email: "",
    message: "",
    ticketNumber: 0,
  });
function makeTicketNumber() {
    setComplaints(...complaint, (ticketNumber) => ticketNumber +1);
  }
function randomNumberGenerator() {
    setRng(Math.floor(Math.random() * (maxValue - minValue + 1) + minValue));
    // complaint.ticketNumber = rng;
  }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Usually, useState() is used with primtive values like strings and numbers or booleans. If you need to save the object, you need to be sure you save the new object every time, otherwise React will not see the changes (it uses just plain a === b comparison).

So you can either split your variables on several useState() calls

const [email, setEmail] = useState(initialEmail)
const [ticketNumbers, setTicketNumber] = useState(initialNumbers)

or use such pattern for updating values:

setComplaint({...complaint, ticketNumber: 10})

Update.

setComplaint() can take the function as an argument, that provides the prevState value. If you want to use it for some reason, you can write it in that way:

setComplaint(prevComplaint => {
  return {
    ...prevComplaint,
    ticketNumber: prevComplaint.ticketNumber + 1,
  }
})

but that's a bulkier solution.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Whatever you set up within setCompaints() will turn into your new state,

Right now, that is the complaint object + a function, which is probably not what you want.

Try this:

function makeTicketNumber() {
    return setComplaints({...complaint, ticketNumber: ticketNumber + 1});
  }
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