1

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 ?

2
  • I feel like there is a typo on this line: const [state, setState] = useState({ .., val: '' }) What is the value you are trying to initialise here? Commented Oct 25, 2020 at 8:12
  • Empty string as initialised value for val, when user click submit btn, I am trying to change value of val by calling setState from child component by changing clickedSubmit to true but state is not updating immediately in handleOnSubmit function. Commented Oct 25, 2020 at 8:26

1 Answer 1

1

Because the change of state is asynchronous Therefore you will not be able to check the state of the state immediately

You can follow it with the useEffect function

like this

useEffect(()=>{
    console.log("useEffect state",state)
},[staet])
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I see value in useEffect function, but I can't find a way to get only the updated value using useEffect and pass to handleOnSubmit function. Now, I made another button to save that value and then another button to save the final values and it works.
@KaungKhantZaw 👍🏽

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.