#Next js server actions

12 messages · Page 1 of 1 (latest)

flat vortex
#

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)

haughty stumpBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

craggy palm
#

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
    );
};
trail leaf
#

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

craggy palm
trail leaf
#

"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 @craggy palm 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