I am using hooks to set varibale as such:
const [test1, setTest1] = useState('')
const [test2, setTest2] = useState('')
The value of test 1 and test2 are set after userinput onChnage={(e)=>setTest1(e.target.value)} and onChnage={(e)=>setTest2(e.target.value)}
Now is it possible to access the value of test1 and test2 in callback function? I have function that gets called on form submit button click as below but I am getting test1 and test2 as undefined.
const onHandleSubmit = useCallback( (event) => {
console.log(test1)
console.log(test2)
let data = {
test1 : test1,
test2 : test2
}
dispatch({type: 'send/data', data:data});
},[]);
You need to write the variables used in the callback into the observations array as shown below:
const onHandleSubmit = useCallback( (event) => {
console.log(test1)
console.log(test2)
let data = {
test1,
test2
}
dispatch({type: 'send/data', data:data});
},[test1, test2]); // <====