In my client I have:
const [error, loginUser, pending] = useActionState(login, null);
loginUser
gets called from a login form:
<form action={loginUser}>....</form>
error
keeps track of the error returned and if not-null then it shows a toast notification:
useEffect(() => {
// this will only fire if the error changes ;(
error && toast.error(error);
}, [error]);
This works the first time a user encounters an error (like the password is too short, but it could be anything etc). But, if the user tries again and encounters the same error then no new toast is shown…but it should even though it is the same error message. Although this is my login page I need the same functionality for my registration page.
I’ve tried the following:
let [error, register, pending] = useActionState(registerUser, null);
useEffect(() => {
// this will only fire if the error changes ;(
error && toast.error(error);
error = null; // reset the error so it triggers useEffect() again..still doesn't work ;(
}, [error]);
But, sadly, this still doesn’t work. Any suggestions?
2
Answers
You can use the setup:
$color{green}{test}$
ServerErrror Component code:
Server Action:
util:
Note:
I am using the next safe action version 6.1.0 https://v6.next-safe-action.dev/ you can use its latest version if you want https://next-safe-action.dev/
i have a little bit complex setup for the login because in my case i need to check for 2fa and user account activation cases too. But you can customize it to fit your needs
Your error is a string, which is primitive. And of course the useEffect will not be triggered if it’s the same error.
Your
login
needs to return an object, and its structure should beIt should work. Try it.