1

I have the following function in which the if statement feels a bit redundant as I'm repeating my calls for sendProfileData twice. Can someone guide me as to how I can make this cleaner, please?

 function editDetails(formData) {
    const initialImage = teacherProfile.value.profilePictureUrl.substring(teacherProfile.value.profilePictureUrl.indexOf("/teacher"))
      if (!formData.fileUploader) {
        sendProfileData(formData, initialImage).then(response => {
          if (response) {
            // After the successful API call, go back to the teachers profile
            router.push({name: ROUTE_NAMES_TEACHER_PROFILE.TEACHER_PROFILE});
          }
        })
      } else {
        uploadProfilePicture(formData.fileUploader).then(response => {
          if (response) {
            sendProfileData(formData, response.filename).then(response => {
              if (response) {
                // After the successful API call, go back to the teachers profile
                router.push({name: ROUTE_NAMES_TEACHER_PROFILE.TEACHER_PROFILE});
              }
            })
          }
        })
      }
    }

// Dispatch action
    function sendProfileData(data, imageUrl) {
      return store.dispatch(SET_PROFILE_DATA, {data, imageUrl});
    }

    function uploadProfilePicture(file) {
      return store.dispatch(UPLOAD_PROFILE_IMAGE, file);
    }
0

1 Answer 1

2

I'd move it to its own function

function uploadProfile(file) {
  sendProfileData(formData, file).then(response => {
      if (response) {
          // After the successful API call, go back to the teachers profile
          router.push({name: ROUTE_NAMES_TEACHER_PROFILE.TEACHER_PROFILE});
      }
  })
}

then call it from two spots

if (!formData.fileUploader) {
  uploadProfile(initialImage)
...
uploadProfilePicture(formData.fileUploader).then(response => {
  if (response) {
    uploadProfile(response.filename)
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your suggestion. The only thing I'm experiencing an issue with is calling uploadProfile(response.filename). If I call the function like this, I won't have access to response.
the provided code doesn't currently access it, what are you trying/want to do with the response?
I need to get the filename from the response itself
add a return inside if and an else with a different return. To cover your bases you might also add a catch with a return
I updated my question to provide a bit more context, as I'm still a bit confused with it
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.