Programmatically submitting forms with server actions
Unanswered
Asian black bear posted this in #help-forum
Asian black bearOP
1. user clicks signin button
2. third party SDK triggers their signin overlay/iframe/whatever
3. promise resolves when the SDK and signin is done
4. component sets the relevant state which is bound to two hidden inputs
5. an effect waits for those two states to be valid
6. submits the form to trigger the server action
given this component, which i've heavily stripped down to just the relevant parts, is there a better way of handling the server action form submission?
the server action function
2. third party SDK triggers their signin overlay/iframe/whatever
3. promise resolves when the SDK and signin is done
4. component sets the relevant state which is bound to two hidden inputs
5. an effect waits for those two states to be valid
6. submits the form to trigger the server action
given this component, which i've heavily stripped down to just the relevant parts, is there a better way of handling the server action form submission?
the server action function
loginServerAction is imported from a co-located actions.ts file that is marked with "use server". is this enough to make just awaiting the function work, without doing all the ref/requestSubmit stuff?function Auth() {
const [email, setEmail] = useState("");
const [token, setToken] = useState("");
const form = useRef<HTMLFormElement>(null);
async function executeSignIn() {
// from a third-party sdk. pops open an overlay and the promise resolves when the login flow is done
const result = await signIn();
if (result.user) {
const token = result.user.token;
if (token && form.current) {
setEmail(result.user.email);
setToken(token);
}
}
}
// submits the form upon sdk login
useEffect(() => {
if (form.current && email && token) {
form.current.requestSubmit();
}
}, [email, token]);
return <>
<button onClick={executeSignIn}>Sign In</button>
<form hidden action={loginServerAction} ref={form}>
<input type="hidden" name="email" value={email} />
<input type="hidden" name="token" value={token} />
</form>
</>
}