Home > other >  My state isn´t updating in a change handler
My state isn´t updating in a change handler

Time:07-25

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: '',
    }
  })

CodePudding user response:

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.

CodePudding user response:

You cannot see your updated state executing immediate log.

To see your update state, please consider adding this line of code.

useEffect(() => console.log(state), [state]);
  • Related