Home > front end >  How can I pass a value into a useState
How can I pass a value into a useState

Time:10-14

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

CodePudding user response:

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});
  }

CodePudding user response:

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.

  • Related