I have a state, that is set to be either true or false in a fetch statement. When the fetch statement is called, the state is not updated until the second time the submit button is pressed.
It is because of that, that whenever I call an if statement right after, my code automatically navigates to my home page, thinking that the adding of a new account is successful.
When I try to set the state to null or false, the ternary statement automatically fires off as well.
I've checked the data by console logging it, and it comes back as "false" when applicable, but still never updates the state
Any insight on how to approach next?
Edit: The fetch is returning a boolean
let navigate = useNavigate();
// Error states
const [successfulAdd, setSuccessfulAdd] = useState(true);
// Function
function handleRegister(e) {
const user = { firstName, lastName, email, password, phone, userName, isAdmin };
if (password !== passwordConfirm) {
setPasswordMatch(false);
} else {
fetch("http://localhost:8080/user/add", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify(user),
})
.then(response => response.json())
.then(data => setSuccessfulAdd(data));
}
if (successfulAdd) {
navigate("../home");
}
}
.
.
.
return (
.
.
.
{/* Username Checker */}
{successfulAdd ? "" : <div class="alert alert-danger" role="alert">
The username you've entered has been taken
</div>}
.
.
.
)
Since Fetch API and setState are both asynchronous, you might want to put the if statement and all logic inside .then(…)
fetch(…)
.then(res => res.json())
.then(json => … //navigate here)
.catch(err => … //set your error state here)