D
D
Denis Sokolov2022-01-07 16:30:28
React
Denis Sokolov, 2022-01-07 16:30:28

Is useState not immediately updated?

My problem is that when I click on the button, the input validation passes and when the validation fails, an error is written to useState and after that I need to find out how many errors. But on the first click, it gives me that 0 errors, although errors are displayed on the page, and if I click the second time, everything is fine

function addFilmHandler() {
    Object.keys(form).forEach((key) => setErrors((state) => ({ ...state, [key]: validateField(key, form[key]) })));
    console.log(Object.keys(errors).filter((key) => errors[key]).length);
 }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2022-01-07
@Casufi

In this handler, you will not see the state change.
If you need to see changes in console.log, then call it in useEffect
https://reactjs.org/docs/hooks-reference.html#usestate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question