I've completed my first JavaScript course and am now following a course on React. I've created a simple backend using Express and MongoDB.
I've created a frontend using npx create-react-app, added axios to communicate with the backend and am using antd for the UI. So far so good! The following code works on my laptop running Windows 10 and Edge 94 to insert a new Year into MongoDB using a simple input:
Client uses:
const onFinish = async (values) => {
await api.createYear(values).then((res) => {
console.log("onFinish", values);
console.log(res);
});
};
API uses:
import axios from 'axios'
const api = axios.create({
baseURL: 'http://localhost:3000/api/v1',
})
export const createYear = values => api.post(`/year`, values)
Server (controller) uses:
const Year = require('../models/year-model')
createYear = (req, res) => {
const body = req.body
if (!body) {
return res.status(400).json({
success: false,
error: 'You must provide a year!',
})
}
const year = new Year(body)
if (!year) {
return res.status(400).json({ success: false, error: err })
}
year
.save()
.then(() => {
return res.status(201).json({
success: true,
id: year._id,
message: 'Year created!',
})
})
.catch(error => {
return res.status(400).json({
error,
message: 'Year not created!',
})
})
}
Server (model) uses:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const yearSchema = new Schema(
{
year: { type: Number, required: true }
},
{ timestamps: false },
)
module.exports = mongoose.model('Year', yearSchema)
However, the same code does not work on my Samsung Galaxy S21 using Edge 93 and Chrome 94. Based on what I found so far, this could be caused by this browser not supporting async/await (ES2017 feature). This could probably be resolved by Babel?
I'm sorry that this part is pretty vague: the information I found is a kind of overwhelming considering my limited experience and all variables involved (React version, Babel version, Babel plugins, Webpack etc). I would gladly provide more information if you could point me in the right direction.
Could anyone perhaps tell me if and how I should change Babel or Webpack to make async/await work in mobile browsers?
If the problem is that async/await doesn't work on those browsers, then I think you can change your .babelrc file to target older browsers.
However, to address @ammar's points, maybe double check that:
I would create a simple html page that looks like this to make sure that this is the problem.
<html>
<head></head>
<body>
<div>TEST PAGE<div>
<div id='test'></div>
<script>
function sleep(t) {
return new Promise(function(resolve) {
setTimeout(resolve, t);
});
}
(async function() {
for (let x = 0; x < 1000; x++) {
document.getElementById('test').innerHTML = x;
await sleep(1000);
}
})();
</script>
<body>
</html>
I would attack it like this:
test.html