简体   繁体   中英

Add element to array setState React

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

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

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

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:

  1. use watch correctly;

  2. forget watch and use classic useEffect :

     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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM