Search code examples
vue.jsvuejs2vuex

How can I seperate functions which are basically the same but use different states? Vue2/Vuex


Ive got a problem since i realized that I break the DRY(Dont repeat yourself) rule. So basically I have 2 modules(movies, cinemas) and few methods in them which look the same but use their module' state. Example: Movies has 'movies' state. Cinemas has 'cinemas' state.

      //cinemas.ts
    @Mutation
  deleteCinemaFromStore(id: string): void {
    const cinemaIndex = this.cinemas.findIndex((item) => item.id === id);
    if (cinemaIndex >= 0) {
      const cinemasCopy = this.cinemas.map((obj) => {
        return { ...obj };
      });
      cinemasCopy.splice(cinemaIndex, 1);
      this.cinemas = cinemasCopy;
    } else {
      throw new Error("Provided id doesn't exist");
    }
  }

   //movies.ts
@Mutation
  deleteMovieFromStore(id: string): void {
    const movieIndex = this.movies.findIndex((item) => item.id === id);
    if (movieIndex >= 0) {
      const moviesCopy = this.movies.map((obj) => {
        return { ...obj };
      });
      moviesCopy.splice(movieIndex, 1);
      this.movies = moviesCopy;
    } else {
      throw new Error("Provided id doesn't exist");
    }
  }

My struggle is: How can I seperate these methods into utils.ts if they have reference to 2 different states?


Solution

  • define another function that take the id, state and store context (this) as parameters :

    function delete(id:string,itemsName:string,self:any){
    
     const itemIndex= self[itemsName].findIndex((item) => item.id === id);
        if (itemIndex>= 0) {
          const itemsCopy = self[itemsName].map((obj) => {
            return { ...obj };
          });
         itemsCopy.splice(itemIndex, 1);
          self[itemsName] = itemsCopy;
        } else {
          throw new Error("Provided id doesn't exist");
        }
    }
    

    then use it like :

         //cities.ts
        @Mutation
      deleteCityFromStore(id: string): void {
       delete(id,'cities',this)
      }
    
      //countries.ts
    @Mutation
      deleteCountryFromStore(id: string): void {
        delete(id,'countries',this)
    }