From c4eb23523c58ad553176228eeda4a1c13b57bc3f Mon Sep 17 00:00:00 2001 From: Isaac Bernat Date: Wed, 5 Nov 2025 12:58:05 +0100 Subject: [PATCH] fix(learn): Improve error handling in state management examples This commit fixes a UX bug in the "City quiz" examples where a submission error would persist on screen even after the user started typing a new answer. The new behavior clears the error message as soon as the user takes a corrective action (typing) or initiates a new submission. The implementation uses a declarative approach by deriving the error's visibility on each render. This design was chosen for two key reasons: 1. It avoids manual state clearing in event handlers, which is a more robust and less error-prone pattern. 2. It respects the tutorial's pedagogical flow by using only concepts introduced up to that point (e.g., `useState`, derived state) without requiring more advanced hooks. --- src/content/learn/managing-state.md | 4 +++- src/content/learn/reacting-to-input-with-state.md | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/content/learn/managing-state.md b/src/content/learn/managing-state.md index ef7b76e04c2..dcd7b0c6d1d 100644 --- a/src/content/learn/managing-state.md +++ b/src/content/learn/managing-state.md @@ -35,6 +35,7 @@ export default function Form() { const [answer, setAnswer] = useState(''); const [error, setError] = useState(null); const [status, setStatus] = useState('typing'); + const showError = status === 'typing' && error && answer === error.failedAnswer; if (status === 'success') { return

That's right!

@@ -49,6 +50,7 @@ export default function Form() { } catch (err) { setStatus('typing'); setError(err); + setError({ message: err.message, failedAnswer: answer }); } } @@ -75,7 +77,7 @@ export default function Form() { }> Submit - {error !== null && + {showError &&

{error.message}

diff --git a/src/content/learn/reacting-to-input-with-state.md b/src/content/learn/reacting-to-input-with-state.md index da559dc0fac..bca51f1a52f 100644 --- a/src/content/learn/reacting-to-input-with-state.md +++ b/src/content/learn/reacting-to-input-with-state.md @@ -57,6 +57,7 @@ async function handleFormSubmit(e) { } function handleTextareaChange() { + hide(errorMessage); if (textarea.value.length === 0) { disable(button); } else { @@ -414,6 +415,7 @@ export default function Form() { const [answer, setAnswer] = useState(''); const [error, setError] = useState(null); const [status, setStatus] = useState('typing'); + const showError = status === 'typing' && error && answer === error.failedAnswer; if (status === 'success') { return

That's right!

@@ -427,7 +429,7 @@ export default function Form() { setStatus('success'); } catch (err) { setStatus('typing'); - setError(err); + setError({ message: err.message, failedAnswer: answer }); } } @@ -454,7 +456,7 @@ export default function Form() { }> Submit - {error !== null && + {showError &&

{error.message}