I am working on a simple mobile app designed to excercise an express.js backend which talks to MongoDB that I created for a class project. The problem I am having is trying to execute one Axios request before the other with .then(). Below is a code snippet that I am trying to execute when a submit button is clicked in the app:
export default function Tile(props) {
const [userText, setUserText] = useState('');
const [passText, setPassText] = useState('');
const [output, setOutput] = useState('Output will display here');
async function submit() {
let req = {username: userText, password: passText};
await axios
.post('/api/register', req)
.catch((response) => console.log(JSON.stringify(response)))
.then(
await axios
.post('/api/login', req)
.catch((res) => setOutput(res.message))
.then((res) => {
if(res.status==200){
setOutput("User creation sucessful and user has been logged in");
save('token', res.data.data);
} else {
setOutput(res.data.message);
}
})
)
}
The first axios call to the route '/api/register' is working fine, however when the second request runs inside the ".then()" of the first, an issue occurs: inside of the route I have written (included in code below), the database is queried to see if a user with the given username (ie, the username that should have just been registered) exists. This query results in a falsy response which causes the commented "if statement" to execute
userRoutes.post('/api/login', async (req, res) => {
const { username, password } = req.body
const user = await User.findOne({ username: username }).lean()
if (!user) { //this statement executes
res.status(298)
return res.json({ message: 'Invalid username/password' })
}
if (await bcrypt.compare(password, user.password)) {
// the username, password combination is successful
//want to see if we need to define this
const token = jwt.sign(
{
id: user._id,
username: user.username
},
JWT_SECRET
)
res.status(200)
return res.json({ message: 'login successfully authenticated', data: token })
}
res.status(298)//actually 400, but axios dumb
res.json({ message: 'Invalid username/password' })
})
Since .then() only executes after the first axios promise is resolved, I would think that the user should be created already and the commented if statment above should not execute, however this is not the case. when I check the database, the user in question does get registered properly (the first axios request succeeds in putting data on the database, but the route of the second call can't find said data when it executes).
I did manage to find a solution that works, however using .then() seems more efficient and like it SHOULD work. The solution using awaits below works exactly the way I want it to, however, I don't understand why my first method using .then() didn't work while using await did. Could someone explain to me the difference and how to make the .then() solution work (if it can work).
async function submit() {
let reg = await axios
.post('/api/register', req)
.catch((res) => console.log(JSON.stringify(res)))
let decide;
(reg == undefined) ? decide = false : (reg.status==200) ? decide = true : decide = false
if(decide){
await axios
.post('/api/login', req)
.catch((res) => setOutput(res.message))
.then((res) => {
if(res.status==200){
setOutput("User creation sucessful and user has been logged in");
save('token', res.data.data);
} else {
setOutput(res.data.message);
}
})
} else {
setOutput(reg.data.message)
}
}
let me know if any other information would be helpful to answer this! Thank You!