ChaoLong Piao
ChaoLong Piao

Reputation: 155

How to use setState function inside the function in functional component?

I am now working on a functional component

const [input_error, setInputError] = useState({
   harvest:false,
   stake:false,
   unstake:false,
   deposit:false,
   withdraw:false,    
   apy:false,
   period:false,
   feeaddress:false,
   harvestfee:false,
   unstakefee1:false,
   unstakefee2:false,
   unstakefee3:false,
   unstakefee4:false,
   unstakefee5:false,
});

function set_value(e) {
   let temp = JSON.parse(JSON.stringify(input_value));
   temp[e.target.name] = e.target.value;
   setInputValue(temp);
}

At this time, I cannot use set_value(e) to modify the state and render it correctly.

Upvotes: 0

Views: 69

Answers (2)

danielm2402
danielm2402

Reputation: 788

If you are using react, I don't recommend doing this for immutability, use the spread operator like this:

setInputError({...input_error, [e.target.name]:e.target.value})

Upvotes: 1

Alex Wang
Alex Wang

Reputation: 21

Because the state is object and you should use json to set the state. So JSON.parse(JSON.stringify(input_value));

to string and to json again.

Upvotes: 1

Related Questions