I'm using the Snackbar component from the Material-UI framework but I can't make it work correctly because the Snackbar shows only the first time, from the second message the Snackbar remain closed.
Here is the code I used to wrap the Snackbar:
import Snackbar from "@material-ui/core/Snackbar";
import { useState } from "react";
export default function Notification({ message }) {
const [value, setValue] = useState(message);
return (
<Snackbar
key={Math.random()}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center'
}}
open={value ? true : false}
autoHideDuration={5000}
message={value}
onClose={() => { console.log('snackbar closed'); setValue('') }}
/>
)
};
I use this component to show the result when the user submit a form. For example when the submit is succesful the message 'operation completed' is shown, but if the server doesn't validate the submission a message error is shown. Here is the code:
function InnerForm({ mode, detail, entity }) {
const isCreateMode = mode === 'create';
const schema = createSchema(entity);
const {
handleSubmit,
formState: { errors },
control,
setValue
} = useForm({
defaultValues: detail,
resolver: yupResolver(schema)
});
const [submitResponse, setSubmitResponse] = useState();
const onSubmit = async data => {
const operation = isCreateMode ?
entity.Client.create(data) :
entity.Client.update(data);
const response = await operation;
setSubmitResponse(response);
console.log(response);
if (response.success) {
if (isCreateMode) {
const autoField = entity.Fields.find(({ auto }) => auto);
if (autoField) {
setValue(autoField.id, response.content[autoField.id]);
}
}
}
};
return (
<>
{
submitResponse ?
submitResponse.success ?
<Notification message='operation completed' /> :
submitResponse.problem ?
<Notification message={submitResponse.problem} /> :
<Notification message='operation failed' />
: null
}
<form onSubmit={handleSubmit(onSubmit)}>
{
entity.Fields.map(field => {
const props = {
control,
id: field.id,
label: field.label,
error: errors[field.id]?.message,
multiline: field.type === 'text',
loadOptions: field.loadOptions,
getOptionLabel: field.getOptionLabel,
readonly: submitResponse?.success || field.auto || (field.key && !isCreateMode)
};
const Component =
field.type === 'string' ? TextInput :
field.type === 'datetime' ? DatetimeInput :
field.type === 'text' ? TextInput :
field.type === 'entity' ? SelectInput :
field.type === 'bool' ? CheckboxInput :
TextInput;
return <Component {...props} />
})
}
<SubmitButton isCreateMode={mode === 'create'} readonly={submitResponse?.success} />
</form>
</>
The test I do is the following:
- First, I compile the form with invalid data and execute the submit => Ok, the snackbar appear with an error message.
- Second, I correct the data and execute a new submit => The submit is succesful, but the success message is not shown