Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My state isn´t updating in a change handler

I have this function to change a value on my state. I don´t know the reason why the state is the same at the beginning and in the end of the function .

const handleChange = (e) => {
        console.log(state);
        setState(prevState =>  ({
            ...prevState,
            form: {
                ...prevState.form,
                [e.target.name]: e.target.value
                
            }
        }));
        console.log(state);
      }

I have a input field, each time the user make changes in that field this function should trigger and update the form state

  const [state, setState] = useState({
    data: data,
    updateModal: false,
    form: {
        id: '',
        name: '',
        content: '',
    }
  })

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

setState receives a callback function that updates the state. console.log line is executed right after the callback was sent to setState (and not yet executed).

setState has also second parameter, which is called after state is updated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading