A custom hook that enhances the useActionState hook with reset function
npm install use-resetable-action-stateA custom hook that enhances the useActionState hook with reset function and payload state.
``tsx:app/page.tsx
'use client';
import { useRef } from 'react';
import { doSomething } from './actions'; // server action
import { useResetableActionState } from 'use-resetable-action-state';
export default function Form() {
const [state, submit, isPending, reset] = useResetableActionState(
doSomething,
null,
);
return (
$3
When the action returns the new state, React will reset the form. But there are cases where you want to keep the form filled. For example, when the new state is an error, you may want to keep the form filled with values that the user has already entered. This way user doesn't have to re-enter the values.
`tsx:app/page.tsx
'use client';
import { useRef } from 'react';
import { doSomething } from './actions';
import { useResetableActionState } from 'use-resetable-action-state';export default function Form({ initialState }: { initialState: { name: string | null, error : stting | null } }) {
const [state, submit, isPending, reset, payload] = useResetableActionState(
doSomething,
initialState,
);
return (
);
}
`In the example above, the form will be initially filled with the
initialState.name if it exists. Then the user can type a different name and submit the form. If the action succeeds, the input will show the new name. If the action fails, the input will show the name from the payload` which is the name that the user has already entered.MIT
Nico Prananta. Website: https://nico.fyi. Twitter: https://twitter.com/2co_p