Next/navigation isn't redirecting after submitting form
Unanswered
Abyssinian posted this in #help-forum
AbyssinianOP
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setIsSubmitting(true);
const response = await fetch(${process.env.NEXT_PUBLIC_API_URL}/login, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
});
const data = await response.json();
if (data.token) {
setCookie("auth_token", data.token);
console.log("Token set, redirecting to /home");
router.push("/home");
} else {
console.log("Error:", data.error);
setError(data.error);
}
setIsSubmitting(false);
};
I can see in the network requests that its fetching the RSC for the home page but it isnt redirecting
The issue happens even outside of the
e.preventDefault();
setIsSubmitting(true);
const response = await fetch(${process.env.NEXT_PUBLIC_API_URL}/login, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
});
const data = await response.json();
if (data.token) {
setCookie("auth_token", data.token);
console.log("Token set, redirecting to /home");
router.push("/home");
} else {
console.log("Error:", data.error);
setError(data.error);
}
setIsSubmitting(false);
};
I can see in the network requests that its fetching the RSC for the home page but it isnt redirecting
The issue happens even outside of the
if(data.token) block2 Replies
AbyssinianOP
It is logging the token set part
And i'm using next/navigation
And i'm using next/navigation
Can you provide a reproducible codeSandbox or something similar to test? Because I tested it and the redirection works as expected. Check the working sandbox here:
https://codesandbox.io/p/devbox/router-push-helper-lvfx33
The relevant code snippet that worked here:
https://codesandbox.io/p/devbox/router-push-helper-lvfx33
The relevant code snippet that worked here:
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
export default function ActionPage() {
const [isSubmitting, setIsSubmitting] = useState(false);
const router = useRouter();
const handleSubmit = async (e: any) => {
e.preventDefault();
setIsSubmitting(true);
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
const data = await response.json();
if (data) {
console.log("Token set, redirecting to /home");
router.push("/home");
} else {
console.log("Error:", data.error);
}
setIsSubmitting(false);
};
return (
<main>
<form onSubmit={handleSubmit}>
<input type="text" name="search" id="search" />
<button type="submit">Search</button>
</form>
</main>
);
}