javascript - how can I refactor my code to ensure there is no repitition
问题描述
I will be calling three different endpoints in a project I am working on. The functions handling the requests are all the same apart from the different urls I will be calling. Below is an example of my code
const handleSubmitPhoneNumber = (e, next) => {
e.preventDefault();
const payload = {
"phone": user.phone
}
const postPhoneNumber = async () => {
setLoading(true)
await axios.post("https://jsonplaceholder.typicode.com/users", payload)
.then(response => {
setLoading(false)
console.log(response)
let res = response;
if (res.data.id === 11) {
next();
}
})
.catch(error => {
console.log(error)
});
}
postPhoneNumber();
}
const handleSubmitVerificationCode = (e, next) => {
e.preventDefault();
const payload = {
"verificationCode": user.verificationCode
}
const postVerificationCode = async () => {
setLoading(true)
await axios.post("https://jsonplaceholder.typicode.com/users", payload)
.then(response => {
setLoading(false)
console.log(response)
let res = response;
if (res.data.id === 11) {
next();
}
})
.catch(error => {
console.log(error)
})
}
postVerificationCode();
}
how can I write this code to avoid repetition since everything is the same apart from the base urls.
解决方案
为您的帖子请求制作一个功能:
async function POST(url, payload, next) {
setLoading(true)
await axios.post(url, payload)
.then(response => {
setLoading(false)
console.log(response)
let res = response;
if (res.data.id === 11) {
next();
}
})
.catch(error => {
console.log(error)
})
}
然后你可以像这样在你的代码中使用这个函数:
const handleSubmitPhoneNumber = (e, next) => {
e.preventDefault();
const payload = {
"phone": user.phone
}
POST("https://jsonplaceholder.typicode.com/users", payload, next)
const handleSubmitVerificationCode = (e, next) => {
e.preventDefault();
const payload = {
"verificationCode": user.verificationCode
}
POST("https://jsonplaceholder.typicode.com/users", payload, next)
}
推荐阅读
- apache-spark - Spark GraphFrames High Shuffle 读/写
- c - 在 while 条件下使用 strcmp 来中断循环
- machine-learning - 处理不平衡的时间序列数据
- center - 将gallerz居中并将h1放在它上面
- swift - 播放音频流PCMBuffer、AVAudioPCMBuffer
- asp.net-core - 使用 nswagger studio 在 .net Core 中获取 Iactionresult 的结果
- go - go tool dist: FAILED: not a Git repo; 必须在 $GOROOT 中放置一个 VERSION 文件
- numpy - Numpy 高级索引:广播是如何发生的?
- javascript - 反应原生导航5慢渲染?
- javascript - 如何告诉本地节点模块所需的 dll 存储在哪里?