I am attempting to set up basic CRUD between a react/redux frontend using MUI and a REST API.
My basic component is as follows:
const UserForm = ({open = false, onClose=() => {}}) => {
const dispatch = useDispatch();
const user = useSelector(currentUser) || {};
let {
firstName = '',
} = user;
const handleSave = () => {
const newUser = {
firstName,
}
// update existing profile
dispatch(updateUser(newUser));
onClose();
}
const handleCancel = () => {
onClose();
}
return (
<Modal open={open} onClose={handleCancel}>
<Box>
<FormControl>
<div>
<TextField sx={halfWidthInputStyle} label="First Name" name="first_name" defaultValue={firstName} onChange={(e) => firstName = e.target.value} error={firstName === ''} />
<Button type="button" onClick={handleSave}>Save</Button>
</div>
</FormControl>
</Box>
</Modal>
)
}
export { UserForm }
Above is my first attempt at error handling. This fails in that it does not update when the user changes the data in the TextField.
After digging around I read that in order for the error
attribute to work properly it must referece a state variable. Therefore I tried the following:
const UserForm = ({open = false, onClose=() => {}}) => {
const dispatch = useDispatch();
const user = useSelector(currentUser) || {};
const [firstName, setFirstName] = useState('');
let {
firstName = '',
} = user;
const handleSave = () => {
const newUser = {
firstName,
}
// update existing profile
dispatch(updateUser(newUser));
onClose();
}
const handleCancel = () => {
onClose();
}
return (
<Modal open={open} onClose={handleCancel}>
<Box>
<FormControl>
<div>
<TextField sx={halfWidthInputStyle} label="First Name" name="first_name" defaultValue={firstName} onChange={(e) => setFirstName(e.target.value)} error={firstName === ''} />
<Button type="button" onClick={handleSave}>Save</Button>
</div>
</FormControl>
</Box>
</Modal>
)
}
export { UserForm }
This makes the error handling work, but it introduces a new, problem. my defaultValue no longer loads because useState is defaulting to ” due to redux returning an empty response on initial render (I think).
So I can’t have my cake and eat it too. Either I have error handling, or I can edit my existing data, but not both. I feel like this should be easier, I’m just trying to make a basic form here.