Next js server actions
Unanswered
Cuban Crocodile posted this in #help-forum
Cuban CrocodileOP
I have two server actions for one form. The form looks exactly the same in two places (different routes), but it is used once to create a user and once to update user data. Can I use the usePathname hook to specify an action for useFormState. I mean e.g
const pathname = usePathname()
const action = pathname === "/create"? action1 : action2
const [state, dispatch] = useFormState(action, initialState)
const pathname = usePathname()
const action = pathname === "/create"? action1 : action2
const [state, dispatch] = useFormState(action, initialState)
11 Replies
Plott Hound
yeah, you could do something like this:
const MyComponent = () => {
// Get the current pathname
const pathname = usePathname();
// Determine the action based on the pathname
const action = pathname === "/create" ? action1 : action2;
// Initial state for the form
const initialState = {}; // your initial state here
// Initialize useFormState with the determined action
const [state, dispatch] = useFormState(action, initialState);
// Rest of your component logic
// ...
return (
// Your form JSX
);
};I would rather pass the correct action via a prop
that I hard-write on each page
but otherwise no problem with that
however it will need client-side JS enabled, contrary to directly passing the action with "action="
but anyway if you use "useFormState" I think it already means your form needs client-side JavaScript enabled, to display the form state
@Eric Burel but anyway if you use "useFormState" I think it already means your form needs client-side JavaScript enabled, to display the form state
Plott Hound
you can use useFormState in server components too!
"useFormState lets you make forms interactive before JavaScript has executed on the client. When used without Server Components, it is equivalent to component local state." from React docs indeed, thanks @Plott Hound for the confirmation
In OP case though they should indeed avoid the call to "useParams" and pass the relevant action from props in order to fully benefits from RSCs
Plott Hound
Thanks for clearing that up @Eric Burel I had misunderstood the op question. Also it might be preferable to use the Params prop instead of pathname. That way you can use a dynamic route to determine the type of action and not dip into client components as much.