Interactive form/post/server action best practice
Unanswered
American Crocodile posted this in #help-forum
American CrocodileOP
I have a process I need to implement, and I´m wondering how this can be solved using server side actions.
1. User enters data in form (phone number) and submits.
2. Server side does a fetch and returns 2 piece of relevant info. A token for a proceeding request, and a control code I need to show the user
3. Call the proceeding link with the given token on a long polling basis until it gives me a go ahead and then redirect the user.
So *fyi *this is a very specific auth method using a cert on a phone card. But that is not what is really important here.
The user will get a message on his phone, with the control code, so he can match that with what is on screen.
So the part I´m mostly struggling with is the best way to fire off the secondary call. I guess a
So can I return the control code from the initial call, but fire off on new call, that will do something when that one answers.
So rough code here
1. User enters data in form (phone number) and submits.
2. Server side does a fetch and returns 2 piece of relevant info. A token for a proceeding request, and a control code I need to show the user
3. Call the proceeding link with the given token on a long polling basis until it gives me a go ahead and then redirect the user.
So *fyi *this is a very specific auth method using a cert on a phone card. But that is not what is really important here.
The user will get a message on his phone, with the control code, so he can match that with what is on screen.
So the part I´m mostly struggling with is the best way to fire off the secondary call. I guess a
UseEffectbased on the status response, but I feel that is a bit dirty and this whole interaction has no need to happen client side.So can I return the control code from the initial call, but fire off on new call, that will do something when that one answers.
So rough code here
const [{ controlcode, error }, formAction] = useActionState(loginPhone, {
controlcode: "",
});
<form action={formAction} className="space-y-6">
<label htmlFor="phone">phonenumber</label>
<input type="text" id="phone" name="phone" required />
<SubmitButton />
</form>
{controlcode && <p>{controlcode}</p>}"use server";
export async function loginPhone(prevState: any, formData: FormData) {
const res = await fetch(
'url',
{
method: "POST",
body: JSON.stringify({
phone: formData.get("phone"),
}),
headers: {
"Content-Type": "application/json",
},
}
);
const response = await res.json();
const token = response.token // token I need for further calls, preferably this needs not enter the client side
return { ...prevState, controlcode: response.control_code };
}