Skip to content
Advertisement

React form how to get user data based on a toggle on/off

I have a form in React JS with one toggle/switch. If toggle/switch is on, then two inputs appear in the screen. So i want to get user data if the user types in inputs and the toggle/switch is on and stays on. So if the user types in inputs but he toggles/switches again to off then input values get reset and when he saves the form i must get empty user data(i get the initial values). How can i achieve something like this? I’m checking in submit handler if the switch button is false and im setting the usestate to the initial values, but it doesnt work.

My code:

Form.js

JavaScript

Advertisement

Answer

The issue is that in showCertificationHandler when you toggle the showCertification you are expecting the state update to be immediate.

JavaScript

This is not the case with React state updates, however. React state updates are enqueued and asynchronously processed.

To resolve, move the “reset” logic into an useEffect hook with a dependency on the showCertification state.

JavaScript

For the same reason above, when resetting the states in your submitHandler they are enqueued and asynchronously processed, so console logging the state immediately after will only ever log the state values from the current render cycle, not what they will be on a subsequent render cycle. You can remove the “reset” logic from submitHandler.

JavaScript

Edit react-form-how-to-get-user-data-based-on-a-toggle-on-off

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement