Created
June 26, 2025 22:11
-
-
Save 17twenty/018daf5e77f12ab70625de79eb4d750d to your computer and use it in GitHub Desktop.
Example of using React with useReducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useReducer } from 'react'; | |
const initialFormState: FormState = { | |
name: '', | |
email: '', | |
isSubmitting: false, | |
isSubmitted: false, | |
submitError: null, | |
}; | |
function ProfileForm() { | |
const [state, dispatch] = useReducer(formReducer, initialFormState); | |
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { | |
dispatch({ | |
type: 'UPDATE_FIELD', | |
field: e.target.name as keyof UserProfile, | |
value: e.target.value, | |
}); | |
}; | |
const handleSubmit = async (e: React.FormEvent) => { | |
e.preventDefault(); | |
dispatch({ type: 'SUBMIT_START' }); | |
try { | |
// Simulate API call | |
await new Promise((res) => setTimeout(res, 1000)); | |
dispatch({ type: 'SUBMIT_SUCCESS' }); | |
} catch (error) { | |
dispatch({ type: 'SUBMIT_ERROR', error: 'Submission failed' }); | |
} | |
}; | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input | |
name="name" | |
value={state.name} | |
onChange={handleChange} | |
disabled={state.isSubmitting} | |
/> | |
<input | |
name="email" | |
value={state.email} | |
onChange={handleChange} | |
disabled={state.isSubmitting} | |
/> | |
<button type="submit" disabled={state.isSubmitting}> | |
{state.isSubmitting ? 'Submitting...' : 'Submit'} | |
</button> | |
{state.submitError && <p style={{ color: 'red' }}>{state.submitError}</p>} | |
{state.isSubmitted && <p style={{ color: 'green' }}>Profile updated!</p>} | |
</form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment