首页 > 解决方案 > 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.

标签: javascriptreactjs

解决方案


为您的帖子请求制作一个功能:

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)
}

推荐阅读