I have two components and I want to set new value to state from child component when button is clicked, so I have the following
// parent component
const [clickedSubmit, setClickedSubmit] = useState(false);
const [state, setState] = useState({
..,
val: '',
})
function handleOnSubmit(e) {
e.preventDefault();
setClickedSubmit(true);
console.log(state);
}
// child component
..
useEffect(() => {
if (clickedSubmit) {
setState({
...state,
val: sigRef.current.getTrimmedCanvas().toDataURL("image/png"),
});
}
}, [clickedSubmit])
state.val is empty when I first click the button and only show value after first time, when I console.log outside of handleOnSubmit function, it logs two time which first time is empty and second has value. Why is that happening and how can I only get the state which has updated value inside handleOnSubmit function ?
const [state, setState] = useState({ .., val: '' })What is the value you are trying to initialise here?val, when user click submit btn, I am trying to change value ofvalby callingsetStatefrom child component by changingclickedSubmittotruebut state is not updating immediately inhandleOnSubmitfunction.