Next.js Discord

Discord Forum

Reset or clear state in the useFormState hook

Unanswered
Pacific sandlance posted this in #help-forum
Open in Discord
Pacific sandlanceOP
I'm creating a login form, so when the user enters incorrect credentials, my server action returns an object with the 'message' property. Now, when I close the modal on my webpage, I want to reset the state of the server action so that the alert doesn't persist when re-entering or in the same case for input validation. How can I handle this?


components/modal.tsx

...
const [actionState, formAction] = useFormState(logInAction, { })
...
{actionState.message && <Alert className='-mt-4' text={actionState.message}/>}
...


I want to reset or clear the 'actionState' .


actions/loginaction.tsx

export async function logInAction (_actionState: LogInActionState, formData: FormData): Promise<LogInActionState> {
const formJSON = Object.fromEntries(formData.entries())
console.log(formJSON)
const formSchema = z.object({
username: z
.string()
.trim()
.toLowerCase()
.min(3, 'Username is too short.')
.max(20, 'Username is too long.'),
password: z
.string()
.trim()
.min(6, 'Password is too short.')
.max(15, 'Password is too long.')
})
const validationResults = formSchema.safeParse(formJSON)

if (!validationResults.success) {
return {
success: false,
errors: validationResults.error.formErrors.fieldErrors
}
}

const { data } = validationResults

const badCredentialsResponse = {
success: false,
message: 'Please check your credentials and try again.'
}

const user = await findUserByUsername({ username: data.username })
if (!user) {
return badCredentialsResponse
}

const isValidPassword = await checkPassword({ password: data.password, hashPassword: user.password })
if (!isValidPassword) {
return badCredentialsResponse
}

return {
success: true
}
}

0 Replies