Skip to content

Instantly share code, notes, and snippets.

@fabriciofmsilva
Created August 20, 2019 22:31
Show Gist options
  • Save fabriciofmsilva/ad0310a52c4d06557cf9c4fbc8479986 to your computer and use it in GitHub Desktop.
Save fabriciofmsilva/ad0310a52c4d06557cf9c4fbc8479986 to your computer and use it in GitHub Desktop.
🐞(n)
function trySubmit() {
// Section 1
let spinner = createSpinner();
formStatus.appendChild(spinner);
submitForm().then(() => {
// Section 2
formStatus.removeChild(spinner);
let successMessage = createSuccessMessage();
formStatus.appendChild(successMessage);
}).catch(error => {
// Section 3
formStatus.removeChild(spinner);
let errorMessage = createErrorMessage(error);
let retryButton = createRetryButton();
formStatus.appendChild(errorMessage);
formStatus.appendChild(retryButton)
retryButton.addEventListener('click', function() {
// Section 4
formStatus.removeChild(errorMessage);
formStatus.removeChild(retryButton);
trySubmit();
});
})
}
function FormStatus() {
let [state, setState] = useState({
step: 'initial'
});
function handleSubmit(e) {
e.preventDefault();
if (state.step === 'pending') {
// Don't allow to submit twice
return;
}
setState({ step: 'pending' });
submitForm().then(() => {
setState({ step: 'success' });
}).catch(error => {
setState({ step: 'error', error });
});
}
let content;
switch (state.step) {
case 'pending':
content = <Spinner />;
break;
case 'success':
content = <SuccessMessage />;
break;
case 'error':
content = (
<>
<ErrorMessage error={state.error} />
<RetryButton onClick={handleSubmit} />
</>
);
break;
}
return (
<form onSubmit={handleSubmit}>
{content}
</form>
);
}
let currentState = {
step: 'initial', // 'initial' | 'pending' | 'success' | 'error'
};
function trySubmit() {
if (currentState.step === 'pending') {
// Don't allow to submit twice
return;
}
setState({ step: 'pending' });
submitForm().then(() => {
setState({ step: 'success' });
}).catch(error => {
setState({ step: 'error', error });
});
}
function setState(nextState) {
// Clear all existing children
formStatus.innerHTML = '';
currentState = nextState;
switch (nextState.step) {
case 'initial':
break;
case 'pending':
formStatus.appendChild(spinner);
break;
case 'success':
let successMessage = createSuccessMessage();
formStatus.appendChild(successMessage);
break;
case 'error':
let errorMessage = createErrorMessage(nextState.error);
let retryButton = createRetryButton();
formStatus.appendChild(errorMessage);
formStatus.appendChild(retryButton);
retryButton.addEventListener('click', trySubmit);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment