DEV Community

SirHeadless
SirHeadless

Posted on

I need help with cleaning up duplicated code

Hey,

I would like to show you my react, redux, typescript project that I'm working on. Afterwards I would like you to help me to refactor my duplicated code. I have many functions that are doing the same but I'm not able to put it into one function.

Let's get right into it. The application has something like a file tree structure to store urls. So something like the bookmarks that most browsers provide.

I think it is easy to see that I'm someone who is mainly concentrating on functionality over the look of my application because what I did so far is unbelievable ugly.

Nevertheless I care a lot about clean code. And there is one thing that I just can't figure out how to make it better, even so I'm sure there must be a nice solution.

In my little clip you can see that you can edit every single field of an url by clicking the edit button. Editing the field and clicking the button again will send a request to my backend to update this field. It is working fine but every single button is calling a different function that is doing the same just for an other field.

Here you can see the functions that are toggling the fields of the url to input fields and dispatch an action that the urlFormFields property has been changed.

  toggleIsNameEditField() {
    this.props.urlFormFields.isNameEditField = !this.props.urlFormFields.isNameEditField;
    this.props.dispatch(updateUrlFormFields(this.props.urlFormFields))
  }

  toggleIsDescriptionEditField() {
    this.props.urlFormFields.isDescriptionEditField = !this.props.urlFormFields.isDescriptionEditField;
    this.props.dispatch(updateUrlFormFields(this.props.urlFormFields))
  }

  toggleIsUrlEditField() {
    this.props.urlFormFields.isUrlEditField = !this.props.urlFormFields.isUrlEditField;
    this.props.dispatch(updateUrlFormFields(this.props.urlFormFields))
  }

The property urlFormFields is looks the following

export interface UrlFormFields {
  isNameEditField: boolean,
  isUrlEditField: boolean,
  isDescriptionEditField: boolean,
  isRatingEditField: boolean,
}

My first try was to create a function that looks something like this

  toggleEditField(editField: boolean){
    editField = !editField;
    this.props.dispatch(updateUrlFormFields(this.props.urlFormFields))

  }

But it simply would not work.

Other things came into my mind which just would not work out :(

You can find the code here https://github.com/SirHeadless/FileSystemTree

If you are willing to help me but you would like to run this code locally I would also mock the calls to the back end and put it into a own branch.

I realized from my previous post's on different pages that it is really hard to me to communicate what my problem is and to make it understandable. If you have any question or need help to help me please contact me :)

Any help is highly appreciated!

Top comments (0)