I have useState "setAnswers" (set) and "answers" (get) (answers is array with strings)
and click trigger:
onClick = () => {
setAnswers((prev) => [...prev, e])
setValue(questionKey, answers)
console.log(watch(questionKey))
}
but with ever click i got only previous value
CodePudding user response:
In fact, your console.log is execute before the state finish to be calculated, if you put your console.log on an other place, normally, you find what you want.
Try it, and say me
CodePudding user response:
Your console.log(watch(questionKey))
all time will go wrong on onChange
.
you need use a useEffect
to log or make anything else with state as base.
useEffect(() => {
console.log(watch(questionKey)
}, [questionKey]);
to more info you can read here: https://dev.to/mpodlasin/react-useeffect-hook-explained-in-depth-on-a-simple-example-19ec
CodePudding user response:
I think you are a little bit confused: watch
function from useForm
is used to
Watch specified inputs and return their values.
So console.log(watch(questionKey))
does make no sense.
watch
should be used in this way:
React.useEffect(() => {
const subscription = watch((value, { name, type }) => console.log(value, name, type));
return () => subscription.unsubscribe();
}, [watch]);
You use a useEffect
to subscribe/unsubscribe watch on some form fields, and then in component's body you could call:
const watchSomething = watch(<something>);
and, every time the field called <something>
will change his value, watch
will execute console.log(value, name, type)
.
If you want to print the very last value of a state variable, you should know that setValue, setAnswer
are async functions and its absolutely not guaranteed that on next line you could log the last value.
To solve your problem you have 2 choices:
use
watch
correctly;forget
watch
and use classicuseEffect
:onClick = () => { setAnswers((prev) => [...prev, e]) setValue(questionKey, answers) } useEffect(() => { console.log(questionKey); //<-- here you will print the very last value of questionKey }, [questionKey]);
Here a guide on how to use watch
.