So I’m trying to create a simple login page that redirects to another page after checking credentials and setting a cookie. My API endpoint is working fine as tested with Postman. However, for some reason router.push
isn’t working at all. It sometimes works when I mention a page that doesn’t exist, giving me a 404 error. But other than that I can’t figure out what’s wrong with my code.
I don’t see any errors on the console whatsoever either.
import axios from "axios"
import { useRouter } from "next/router"
import { useState } from "react"
export default function login() {
const [username, setUsername] = useState(null)
const [password, setPassword] = useState(null)
const [error, setError] = useState(false)
const router = useRouter()
const handleClick = async () => {
try {
await axios.post("http://192.168.0.112:3000/api/login", {
username,
password,
});
router.push("/admin");
} catch (err) {
setError(true);
}
};
return (
<div className="container mt-5 d-flex flex-column justify-content-center align-items-center">
<h1 className="display-3">Admin login</h1>
<form className="bg-light p-3">
<div className="mb-3">
<label htmlFor="username" className="form-label">Username</label>
<input type="text" className="form-control" id="username" onChange={(e) => setUsername(e.target.value)} name="username" aria-describedby="emailHelp"/>
</div>
<div className="mb-3">
<label htmlFor="password" className="form-label">Password</label>
<input type="password" className="form-control" id="password" onChange={(e) => setPassword(e.target.value)} name="password"/>
</div>
{error &&<span>Wrong Credentials</span>}
<button className="btn btn-success" onClick={handleClick}>Log in</button>
</form>
</div>
)
}
This page checks the credentials (from an env.local
file) and creates a cookie if the credentials are right, but that’s about it. Any idea how I can get router.push
to start working as expected?