Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!