<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Konrad Straszewski on Medium]]></title>
        <description><![CDATA[Stories by Konrad Straszewski on Medium]]></description>
        <link>https://medium.com/@koonradstraszewski?source=rss-656c9787dff9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UcMuWpSGD8BYf34W4Y1hkw.jpeg</url>
            <title>Stories by Konrad Straszewski on Medium</title>
            <link>https://medium.com/@koonradstraszewski?source=rss-656c9787dff9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:46:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@koonradstraszewski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vue.js + Typescript best practices #5: Class-based fetching with Axios using DTO architecture]]></title>
            <link>https://medium.com/js-dojo/vue-js-typescript-best-practices-5-class-based-fetching-with-axios-using-dto-architecture-a2bf80102162?source=rss-656c9787dff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2bf80102162</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Konrad Straszewski]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 21:01:50 GMT</pubDate>
            <atom:updated>2019-10-22T02:14:10.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JV-liQv_Va530pu6_5Qe4g.jpeg" /></figure><p>Ok, it is actually not only about Vue because you can actually use this architecture in angular or react also, but I will show an example in Vue.js just because Vue is the best.</p><h3>What is Class-based fetching</h3><p>Before I will start explanation I would like to introduce you to a problem. Let’s assume, we have a model User<strong>, </strong>which is a simple example, but <strong>with more complex example it’s getting more sense</strong>. Our <strong>User.ts</strong> looks like this:</p><pre>export interface <strong>IUser </strong>{<br>  id?: number;<br>  email: string;<br>  first_name: string;<br>  last_name: string;<br>  avatar: string;<br>}</pre><p>and now we want to create a list of users so we need to fetch our Users. I&#39;m using simple and free <a href="https://reqres.in/api/users">API </a>that I found for this article and I&#39;m using getter that returns this interface:</p><pre>interface <strong>RequestInterface </strong>{<br>  page: number,<br>  per_page: number,<br>  total: number,<br>  total_pages: number,<br>  data: <strong>IUser</strong>[]<br>}</pre><pre><em>/// Endpoint response interface</em></pre><p>Next, I&#39;m creating a UsersApi service to easily manage my endpoints:</p><pre>export abstract class <strong>UsersApi </strong>{<br>  private static <strong><em>usersAxios </em></strong>= <em>Axios</em>.create();<br><br>  static async <strong><em>getAllUsers</em></strong>(): Promise&lt;<strong>IUser[]</strong>&gt;{<br>    let url = &#39;https://reqres.in/api/users&#39;<br>    let response = await this.<strong><em>usersAxios</em></strong>.get&lt;<strong>RequestInterface</strong>&gt;(url);<br>    return response.data.data;<br>  }<br>}</pre><pre><em>/// Api service</em></pre><p>Ok, so the last thing for me to do is to use this service so inside my component in <strong>mounted </strong>function (it is crucial to use it in mounted because this hook can be <strong>async</strong>!):</p><pre>export default class HomeComponent extends Vue {<br>  private <strong>users</strong>: <strong>IUser</strong>[] = [];<br><br>  async <strong>mounted</strong>(): Promise&lt;void&gt; {<br>    this.<strong>users </strong>= await <strong>UsersApi.<em>getAllUsers</em>()</strong>;<br>  }<br>};</pre><pre><em>/// HomeComponent.vue</em></pre><p>Ok so now I want to create my list by displaying first_name and last_name, so we have 3 options:</p><h3>Option 1 — the bad one</h3><p>The easiest way and the first thing that comes to mind is to display it in the simplest way possible <strong>just write the logic in HTML</strong>:</p><pre>&lt;v-list-item :key=&quot;<strong><em>index</em></strong>&quot; v-for=&quot;(<strong><em>user</em></strong>, <strong><em>index</em></strong>) in users&quot;&gt;<br>  {{<strong><em>user</em></strong>.first_name}} {{<strong><em>user</em></strong>.last_name}}<br>&lt;/v-list-item&gt;</pre><p>And It is ok. It will do the job, but like I said in the beginning, imagine that your model is more complex. This method has <strong>lots of disadvantages</strong>.</p><p>The <strong>first one</strong> and in my opinion the biggest is that in HTML you are <strong>forced to use simple Javascript instead of typescript</strong>, so it is simple to do a typo.</p><p>The <strong>second huge problem</strong> is let’s say you want to use this string of firstName and lastName in lot’s of places, <strong>you will need to write this code</strong><br>{{user.first_name}} {{user.last_name}} every time you want to display a user&#39;s full name.</p><p>So it lacks <strong>types </strong>and <strong>reusability.</strong></p><h3>Option 2 — the ok one</h3><p>You can <strong>create a method</strong> in your component that returns the full name of a user:</p><pre><strong>getUserFullName</strong>(user: User): string{<br>  return `${user.first_name} ${user.last_name}`;<br>}</pre><pre>/// HomeComponent.vue - typescript</pre><p>and use it in HTML like this:</p><pre>&lt;v-list-item :key=&quot;<strong><em>index</em></strong>&quot; v-for=&quot;(<strong><em>user</em></strong>, <strong><em>index</em></strong>) in users&quot;&gt;<br>  {{<strong>getUserFullName</strong>(user)}}<br>&lt;/v-list-item&gt;</pre><pre>/// HomeComponent.vue - html</pre><p>And this is ok because I’ve managed to eliminate the first problem by moving logic to Typescript instead of writing it in simple Javascript inside HTML.</p><p>Wait, but what about <strong>reusability?</strong> Hmm… It’s better, for sure, but what about displaying user full name in other components? <strong>I will need to create the same function over and over again… ugh…</strong></p><p>So this solution is ok, but we can make it better!</p><h3>Option 3 — the best one</h3><p>I believe that sometimes to create an intuitive mechanism, implementation of it can be complex but it will pay off in the long run.</p><p>So the simplest way to use it would be just writing a getter inside a User object, that would allow us to use it like this:</p><pre>&lt;v-list-item :key=&quot;<strong><em>index</em></strong>&quot; v-for=&quot;(<strong><em>user</em></strong>, <strong><em>index</em></strong>) in users&quot;&gt;<br>  {{<strong>user.fullName</strong>}}<br>&lt;/v-list-item&gt;</pre><pre>/// HomeComponent.vue - html</pre><p>To do this you will need a <strong>Class-based fetching</strong> data architecture that implements more <strong>Model-Driven Design</strong> to the frontend. The assumption is simple, <strong>UserApi fetch function returns not an Interface but a Class</strong>, and that’s about it, but how to achieve it?</p><p>I like to have lots of interfaces and have an interface for every class. It may be unnecessary, but I will leave IUser interface alone and implement in User class, So my User.ts file looks like this:</p><pre>export interface <strong>IUser </strong>{<br>  id?: number;<br>  email: string;<br>  first_name: string;<br>  last_name: string;<br>  avatar: string;<br>}<br><br>export <strong>class UserDTO implements IUser</strong>{<br>  id?: number;<br>  avatar: string = &#39;&#39;;<br>  email: string = &#39;&#39;;<br>  first_name: string = &#39;&#39;;<br>  last_name: string = &#39;&#39;;<br><br>}<br><br>export default <strong>class User extends UserDTO</strong> {</pre><pre>  constructor(dto: UserDTO){<br>    super();<br>    <strong><em>Object</em>.assign(this, dto);</strong><br>  }<br><br>  get <strong>fullName</strong>(): string {<br>    return `${this.first_name} ${this.last_name}`;<br>  }<br>}</pre><pre><em>/// User.ts</em></pre><p>as you can see I’ve created 2 classes:<br>1. UserDTO<br>2. User</p><p>The first one I’m using just to declare default values and represent a model that is returning in response from backend so this is <strong>Data Transfer Object.</strong></p><p>And to parse Dto object to have all of the property set by UserDto I need to do one trick and it is this <strong><em>Object</em>.assign(this, dto) </strong>line. I know it stinks but it is the best solution I found.</p><p>The second one represents a class that I want to have and use when referring to the <strong>User Model</strong>. This adds an additional layer of abstraction to our architecture, so It makes it easier to mock something here, but also allow us to add functions and getters or whatever we want to the model. And as you can see there is our fullName getter there.</p><p><strong>But!</strong> And this is an important part, we need to add mapping to UserApi service because backend returns an array of UserDTO objects and we want an array of User objects. So this mapping is ultra simple and looks like this:</p><pre>static async <strong><em>getAllUsers</em></strong>(): Promise&lt;<strong>User[]</strong>&gt;{<br>  let url = &#39;https://reqres.in/api/users&#39;<br>  let response = await this.<em>usersAxios</em>.get&lt;RequestInterface&gt;(url);<br>  return response.data.data<strong>.map(userDto =&gt; new User(userDto));</strong><br>}</pre><p>So now <strong>getAllUsers() </strong>function returns <strong>Promise&lt;User[]&gt;</strong> instead of <strong>Promise&lt;IUser[]&gt;.</strong></p><p>And that’s it now you can create new properties and new getters inside a class and have a better clearer look on your Model.</p><p>If you want to check full repo <a href="https://github.com/kstraszewski/playground-vue/tree/class-based-fetching">click here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2bf80102162" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/vue-js-typescript-best-practices-5-class-based-fetching-with-axios-using-dto-architecture-a2bf80102162">Vue.js + Typescript best practices #5: Class-based fetching with Axios using DTO architecture</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js + Typescript best practices #4: create better $emit()]]></title>
            <link>https://medium.com/js-dojo/vue-js-typescript-best-practices-create-better-emit-b98712819411?source=rss-656c9787dff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b98712819411</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Konrad Straszewski]]></dc:creator>
            <pubDate>Thu, 10 Oct 2019 09:17:19 GMT</pubDate>
            <atom:updated>2019-10-15T22:01:00.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*uWQOjkzzYAxSqlRaHK4pWA.png" /></figure><p>I’ve never liked this event communication between parent and child component that forces you to pass prop to a child and then emit value with key update:&lt;prop_name&gt; , so I decided to find a better solution to this problem with a little typescript magic.</p><h3>Creating example</h3><p>Let’s create a simple example with parent and child components.</p><p>Here is a parent component:</p><pre>&lt;template&gt;<br>  &lt;<strong>HelloWorld </strong>:msg.sync=&quot;msg&quot;/&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;<br>export default Vue.extend({<br>  name: &#39;App&#39;,<br>  data: () =&gt; ({<br>    <strong>msg</strong>: &#39;Marko&#39;,<br>  }),<br>});<br>&lt;/script&gt;</pre><p>and child component</p><pre>&lt;template&gt;<br>  &lt;v-container&gt;<br>    &lt;v-layout text-center wrap&gt;<br>      &lt;v-flex&gt;{{<strong>msg</strong>}}&lt;/v-flex&gt;<br>    &lt;/v-layout&gt;<br>  &lt;/v-container&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;<br>@Component<br>export default class HelloWorld extends Vue{<br>  @Prop({required: true, type: String,})<br>  public <strong>msg</strong>!: string;<br>}<br>&lt;/script&gt;</pre><h3>Ditching “update:” prefix</h3><p>First of all, I wanted to ditch an update: prefix. I’ve started with extending a Vue.prototype with a new function, let’s call it $sync and declare it in main.ts like that (more about extending Vue.prototype <a href="https://vuejs.org/v2/cookbook/adding-instance-properties.html#The-Importance-of-Scoping-Instance-Properties">here</a>):</p><pre>Vue.prototype.<strong>$sync </strong>= function(key: string, value: any) {<br>  this.$emit(<strong>`update:${key}`</strong>, value);<br>};</pre><p>Ok, so now I need to tell typescript that from now Vue class has $sync function. To do that I need to create vue.d.ts in src/types folder.</p><pre>declare module &#39;vue/types/vue&#39; {<br>  interface <strong>Vue </strong>{<br>    $sync(key: string, value: any): void;<br>  }<br>}</pre><p>We will change this <strong>string </strong>and <strong>any </strong>latter. Now we can add a button that uses our brand new <strong>$sync</strong> function like this:</p><pre>&lt;template&gt;<br>  &lt;v-container&gt;<br>    &lt;v-layout text-center wrap&gt;<br>      &lt;v-flex&gt;{{<strong>msg</strong>}}&lt;/v-flex&gt;<br>      &lt;v-btn depressed primary @click=&quot;<strong>respond</strong>()&quot;&gt;Respond&lt;/v-btn&gt;<br>    &lt;/v-layout&gt;<br>  &lt;/v-container&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;<br>@Component<br>export default class HelloWorld extends Vue{<br>  @Prop({required: true, type: String,})<br>  public <strong>msg</strong>!: string;</pre><pre>  public <strong>respond</strong>(){<br>    this.<strong>$sync</strong>(<strong>&#39;msg&#39;</strong>, `${this.msg} Polo`);<br>  }<br>}<br>&lt;/script&gt;</pre><h3>Adding types for $emit key</h3><p>Ok, so now I would like to get some IntelliSense from IDE for our key and also change $sync for a generic method to type value that is emitting.</p><p>Here we can use my favorite keyword which is <strong>keyof</strong>, to get better typing. So let’s change our vue.d.ts a little to look like this:</p><pre>declare module &#39;vue/types/vue&#39; {<br>  interface Vue {<br>    $sync(key: <strong>keyof this</strong>, value: any): void;<br>  }<br>}</pre><p>Ok so now we receive a greate code autocompletion and also typescript compiler can check our passed string</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*x4Ze9ctNBJuLWwkQw0sExw.png" /></figure><p>Like u can see here is a proposition to use string msg for a parameter. But when we want to use something different like msg1 we get a compiler error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*bx2o0JggfEW5b8ndBAUvYQ.png" /><figcaption>The argument of type ‘“msg1”’ is not assignable to parameter of type ‘keyof this’.</figcaption></figure><p>So now we can only pass a prop that exists and is declared in our class that extends Vue.</p><h3>Generic $sync</h3><p>The last thing to add is just making this $sync method a generic one and finally declared it like this:</p><pre>declare module &#39;vue/types/vue&#39; {<br>  interface Vue {<br>    $sync<strong>&lt;T&gt;</strong>(key: keyof this, value: <strong>T</strong>): void;<br>  }<br>}</pre><p>So here is our final example child component:</p><pre>&lt;template&gt;<br>  &lt;v-container&gt;<br>    &lt;v-layout text-center wrap&gt;<br>      &lt;v-flex&gt;<br>        {{<strong>msg</strong>}}<br>      &lt;/v-flex&gt;<br>      &lt;v-btn depressed primary @click=&quot;respond()&quot;&gt;Respond&lt;/v-btn&gt;<br>    &lt;/v-layout&gt;<br>  &lt;/v-container&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;<br>import {Component, Prop} from &#39;vue-property-decorator&#39;;<br>import Vue from &#39;vue&#39;;</pre><pre>@Component<br>export default class HelloWorld extends Vue{<br>  @Prop({required: true, type: String,})<br>  public <strong>msg</strong>!: string;</pre><pre>  public respond(){<br>    <strong>this.$sync&lt;string&gt;(&#39;msg&#39;, `${this.msg} Polo`);</strong><br>  }<br>}<br>&lt;/script&gt;</pre><p>and every time we will use this component like this</p><pre>&lt;HelloWorld <strong>:msg.sync=&quot;variable&quot;</strong>/&gt;</pre><p>we will get <strong>variable</strong> to be updated with all key completion support and type checking. The <a href="https://github.com/kstraszewski/playground-vue/tree/%24sync">full example is here</a> on my playground repository <em>$sync</em> branch</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b98712819411" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/vue-js-typescript-best-practices-create-better-emit-b98712819411">Vue.js + Typescript best practices #4: create better $emit()</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js + Typescript best practices #3: Create a custom hook component like mounted or created]]></title>
            <link>https://medium.com/js-dojo/create-a-custom-component-life-circle-hook-for-vue-js-with-typescript-b624559bceac?source=rss-656c9787dff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b624559bceac</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Konrad Straszewski]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 20:11:03 GMT</pubDate>
            <atom:updated>2019-10-15T21:59:42.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IHOwnnSFmXRmzGB6XPbYQ.jpeg" /></figure><p>I have a huge problem with watchers. I hate this solution…</p><p>I hate to use watchers in typescript class-based components because, in my opinion, it is just the dirtiest way to check a state change. Unfortunately,. sometimes it is just the easiest and the fastest way to manage changes, but I would love to have a custom Hook like <strong>mounted </strong>or <strong>created</strong>.</p><p>Last time I had a situation that I had 1 parent component with one object property and lots of child components and every child component has required a prop that is this one property and needed an onChange event inside.</p><p>So let’s assume simple example with similar architecture but with a smaller scale. I’ve created an app that had 1 main model <strong>Car</strong>, and also a mechanic component that lets us upgrade car and journal component that keeps all the changes.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;{{car}}&lt;/p&gt;<br>    &lt;mechanic :car=&quot;car&quot;&gt;&lt;/mechanic&gt;<br>    &lt;journal :car=&quot;car&quot;&gt;&lt;/journal&gt;<br>    ...<br>    &lt;more-children :car=&quot;car&quot;&gt;&lt;/more-children&gt;  <br>&lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;</pre><pre>@Component<br>export default class HelloWorld extends Vue {<br>    public car = new Car();<br>}<br>&lt;/script&gt;</pre><p>and here is our <strong>Car </strong>class</p><pre>export class Car {<br>  color: string = &#39;red&#39;;<br>  wheelSize: number = 17;<br>  engineHP: number = 120;<br>  mark: string = &#39;Volkswagen&#39;;<br>  productionYear: number = 1999;<br>}</pre><p>Ok, so now we want to have a function in <strong>Journal </strong>component that is called every time when car object is changed to keep our changes displayed.</p><p>First of all, I was thinking about some intersection in the computed getter, but it is also not the best solution to call a function inside getter. Vue documentation offers us a “<em>watch</em>” prop, but I do not want to have a watcher in every component so I was thinking about having a function that works in some way like <strong>mounted </strong>or <strong>created </strong>hook<em> </em>but 100% custom, not predefined by Vue team.</p><h3>Creating UI for example app</h3><p>I started with creating a proxy Class that extends Vue class</p><pre>export class VueCarWatcher extends Vue {<br>  @Prop() private car!: Car;<br>}</pre><p>then every component (mechanic, journal, etc…) instead of extending Vue can extend <strong>VueCarWatcher </strong>that have <em>car </em>prop declared.</p><p>Next step was to create a hook, so I started creating a hook with a new interface, and to avoid magic value I’ve created a constant with the function name because I will use it later:</p><pre>const ON_CAR_CHANGE_FUNCTION_NAME = &#39;onCarChange&#39;;</pre><pre>export interface onCarChange {<br>  [ON_CAR_CHANGE_FUNCTION_NAME](newCar: Car, oldCar: Car): void;<br>}</pre><p>Now I can create a Mechanic.vue and Journal.vue components</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;button @click=&quot;car.engineHP = 155&quot;&gt;Change engine&lt;/button&gt;<br>    &lt;button @click=&quot;car.wheelSize = 18&quot;&gt;Change wheels&lt;/button&gt;<br>    &lt;button @click=&quot;car.color = &#39;blue&#39;&quot;&gt;Change color&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;</pre><pre>@Component<br>export default class Mechanic extends VueCarWatcher {}<br>&lt;/script&gt;</pre><p>Here is <strong>Mechanic </strong>component that has some function to change our car in the simplest possible way (ok, this one actually could be functional, but let’s say we want to create a more complicated component and we just want types here). Next one will be <strong>Journal </strong>for displaying changes.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p :key=&quot;<strong><em>index</em></strong>&quot; v-for=&quot;(<strong><em>element</em></strong>, <strong><em>index</em></strong>) in journalElements&quot;&gt; <br>   {{<strong><em>element</em></strong>.content}} on {{<strong><em>element</em></strong>.date}}&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script lang=&quot;ts&quot;&gt;</pre><pre>interface JournalElement{<br>  content: string;<br>  date: Date;<br>}</pre><pre>@Component<br>export default class Journal extends VueCarWatcher implements onCarChange{<br>  private journalElements: JournalElement[] = [];</pre><pre>  onCarChange(newCar: Car, oldCar: Car): void {<br>    this.journalElements.push({<br>      content: `car has been changed from ${<strong><em>JSON</em></strong>.stringify(oldCar)} to ${<strong><em>JSON</em></strong>.stringify(newCar)}`,<br>      date: new <strong><em>Date</em></strong>(),<br>    });<br>  }<br>}<br>&lt;/script&gt;</pre><p>ok, so as you can see here I implemented <strong><em>onCarChange </em></strong>interface here. So now we can launch our app, and nothing will happen but now it is time to create a hook, so it is time for the main part.</p><h3>Creating a custom Hook</h3><p>Now we want our <strong><em>onCarChange </em></strong>function to be called every time when <em>car </em>object will change, so, unfortunately, we need our Watcher but we will need only one, so it doesn’t hurt very much. So I’ve needed to create Watcher that calls this function inside <strong>VueCarWatcher </strong>class. Here is how it is done:</p><pre>const ON_CAR_CHANGE_FUNCTION_NAME = &#39;onCarChange&#39;;</pre><pre>export interface onCarChange {<br>  [ON_CAR_CHANGE_FUNCTION_NAME](newCar: Car, oldCar: Car): void;<br>}</pre><pre>export class VueCarWatcher extends Vue {<br>  @Prop() private car!: Car;</pre><pre>  @Watch(&#39;car&#39;, {deep: true,})<br>  private carWatcher(newCar: Car, oldCar: Car) {<br>    const carHandler = this[ON_CAR_CHANGE_FUNCTION_NAME]<br>    if(carHandler &amp;&amp; typeof carHandler === &#39;function&#39;) {<br>      carHandler(newCar, oldCar);<br>    }<br>  }<br>}</pre><p>As you can see, I’ve added an function that tries to call a function from <strong><em>this</em></strong>, and also I’ve checked if it exists and it is a function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b624559bceac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/create-a-custom-component-life-circle-hook-for-vue-js-with-typescript-b624559bceac">Vue.js + Typescript best practices #3: Create a custom hook component like mounted or created</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js + Typescript best practices #2: Using fully typed Vuex mutations with vuex-typescript]]></title>
            <link>https://medium.com/js-dojo/using-fully-typed-vuex-mutations-with-vuex-typescript-7597f56eceec?source=rss-656c9787dff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7597f56eceec</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Konrad Straszewski]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 00:05:43 GMT</pubDate>
            <atom:updated>2019-10-17T02:06:39.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3vfoZyP_E579jVj_TTzdA.png" /></figure><p>Hi, I really like the idea of vuex and having a global store, but I always hated using mutations by passing magic-string to the commit function. This solution just begs for a typo. So when typescript gets popular I was really excited that maybe someone will fix Vuex mutations so you don’t need to use magic-strings, but unfortunately, It didn’t happened :/</p><p>I’ve decided to set myself a goal to create store service with actions that are based on fully-typed mutations. So I created a simple vuex module that looks like this:</p><pre><strong>export const </strong>ClientStoreModule = {<br>  namespaced: <strong>false</strong>,<br>  state: <strong>new </strong>ClientStoreState(),<br>  getters: {<br>    clients(state: ClientStoreState) {<br>      <strong>return </strong>state.Clients;<br>    },<br>  },<br>  mutations: {<br>    setClients(state: ClientStoreState, clients: Array&lt;Client&gt;) {<br>      state.Clients = clients;<br>    },<br>    addClient(state: ClientStoreState, client: Client) {<br>      state.Clients.push(client);<br>    },<br>  },<br>};</pre><p>And here is my state class:</p><pre><strong>export class </strong>ClientStoreState {<br>  Clients: Array&lt;Client&gt; = [];<br>}</pre><p>My goal was to achieve mutations that can be used more or less like this:</p><pre>commit&lt;Client&gt;(ClientStoreModule.mutations.addClient, client);</pre><p>So I started from google this problem and I found a great library called vuex-typescript and here is a link:</p><p><a href="https://github.com/istrib/vuex-typescript">istrib/vuex-typescript</a></p><p>This library is cool but it forced you to use your commits like this:</p><pre>let storeApi = getStoreAccessors&lt;ClientStoreState, RootState&gt;(&#39;&#39;)<br>let commit = storeApi.commit(ClientStoreModule.mutations.addClient)<br>commit(this.$store, client)</pre><blockquote>For full documentation go to the link I’ve put above</blockquote><p>And again, ok it’s waaay cooler than the old fashion <br>commit(&#39;addClient&#39;, client). Now we have our mutations fully typed! But this solution is just long and it takes a lot of code to use it. So I wrapped it up a little.</p><p>I created an abstract class to extends my future service with vuex actions:</p><pre><strong>import </strong>{getStoreAccessors, MutationHandlerWithPayload} <strong>from </strong>&#39;vuex-typescript&#39;;</pre><pre><strong>export default abstract class </strong>BaseStoreService&lt;T&gt; {<br>  <strong>protected </strong>mutations!: Record&lt;<strong>string</strong>,(state: T, payload: <strong>any</strong>) =&gt; <strong>void</strong>&gt;;<br>  <strong>protected </strong>storeApi = getStoreAccessors&lt;T, RootState&gt;(&#39;&#39;);</pre><pre>  <strong>protected </strong>commit&lt;TPayload&gt;(handler: (MutationHandlerWithPayload&lt;T, TPayload&gt;), payload: TPayload) {<br>    <strong>this</strong>.storeApi.commit(handler)(store, payload);<br>  }<br>}</pre><blockquote>I’m using vuex modules so my RootState is just an interface of my whole vuex store.</blockquote><p>Ok now it is time to create my dream vuex service that handles actions:</p><pre><strong>class </strong>ClientStore <strong>extends </strong>BaseStoreService&lt;ClientStoreState&gt; {</pre><pre>  <strong>public </strong>mutations = ClientStoreModule.mutations;</pre><pre>  <strong>async </strong>addClient(newClient: Client) {<br>    <strong>this</strong>.commit&lt;Client&gt;(<strong>this</strong>.mutations.addClient, newClient);<br>  }</pre><pre><strong>  async </strong>fetchClients(clients) {<br>    <strong>this</strong>.commit(<strong>this</strong>.mutations.setClients, clients);<br>  }<br>}<br><strong>export default new </strong>ClientStore();</pre><p>And here we go now we can use our fully-typed service with fully-typed mutations like this ClientStore.addClient(client) and gain typescript great code completion everywhere without using magic-strings anywhere.</p><p>Ok, so we handle our mutations in this nice way, but what about getters?</p><p>Class bassed vue component written in typescript force you to use this syntax:</p><pre>@Getter clients!: Array&lt;Client&gt;;</pre><p>And again it is not so bad, but let’s say you want to reformat your clients variable. You need to remember to change these names everywhere and it’s just messy.</p><p>Let’s go back to our vuex-typescript library. Just like commit it has read function. So I’ve extended my BaseStoreService with the second function:</p><pre><strong>import </strong>{getStoreAccessors, GetterHandler, MutationHandlerNoPayload, MutationHandlerWithPayload} <strong>from </strong>&#39;vuex-typescript&#39;;</pre><pre><strong>export default abstract class </strong>BaseStoreService&lt;T&gt; {<br>  <strong>protected </strong>mutations!: Record&lt;<strong>string</strong>,(state: T, payload: <strong>any</strong>) =&gt; <strong>void</strong>&gt;;<br>  <strong>protected </strong>storeApi = getStoreAccessors&lt;T, RootState&gt;(&#39;&#39;);</pre><pre><strong>  protected </strong>commit&lt;TPayload&gt;(handler: (MutationHandlerWithPayload&lt;T, TPayload&gt;), payload: TPayload) {<br>    <strong>this</strong>.storeApi.commit(handler)(store, payload);<br>  }<br>  <strong>protected </strong>read&lt;TResult&gt;(handler: GetterHandler&lt;T, RootState, TResult&gt;): TResult {<br>    <strong>return this</strong>.storeApi.read&lt;TResult&gt;(handler)(store);<br>  }<br>}</pre><p>so now I can add to my ClientStore service typescript getter with fully typescript support and write my fully-typed getter like this:</p><pre><strong>get </strong>getClients() {<br>  <strong>return this</strong>.read&lt;Array&lt;Client&gt;&gt;(ClientStoreModule.getters.clients)<br>}</pre><p>and that’s it we have are fully-typed getters and fully-typed mutations inside our ClientStore service and we can access our vuex getters like this:<br>ClientStore.getClients()</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7597f56eceec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/using-fully-typed-vuex-mutations-with-vuex-typescript-7597f56eceec">Vue.js + Typescript best practices #2: Using fully typed Vuex mutations with vuex-typescript</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js + Typescript best practices #1: Creating modal service that handling dialogs as promise]]></title>
            <link>https://medium.com/js-dojo/how-to-create-a-modal-service-in-vue-js-43b6b2e7057?source=rss-656c9787dff9------2</link>
            <guid isPermaLink="false">https://medium.com/p/43b6b2e7057</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Konrad Straszewski]]></dc:creator>
            <pubDate>Sat, 09 Feb 2019 23:44:11 GMT</pubDate>
            <atom:updated>2019-10-18T09:48:03.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vue.js + Typescript best practices #1: How to create a modal service in Vue.js that is handling dialogs as a Promise to gain reusability of a modal components</h3><p>If anyone of you ever used modals in angular.js or Angular bootstrap components, then you are familiar with $modalService.open(component, data) syntax that returns Promise. If not, here is an <a href="https://ng-bootstrap.github.io/#/components/modal/examples#component">example</a>. Every big component library in vue.js has this weird syntax that force you to create an HTML modal element inside your component and trigger modal by this.$refs or setting a proper flag inside a v-modelproperty. My problem with this solution is that the modal written this way is lacking reusability and is just not clean enough.</p><p>So I decided to write my own service that generates a modal from every VueComponent with its own isolated scope. My first goal was to create a service that allows you to use every component you want, pass it to theopen()function and create a modal from it. Idea was to create something that can be called like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUVq2OIlwem5PAH-PClbwQ.png" /><figcaption>Usage of modalService inside - ParentComponent.vue</figcaption></figure><p>So $modalService generates a Promise which starts a modal. On a close event of a modal, service is resolving a Promise from a parent component and returning data from a generated modal (child) component.</p><p>The second goal was to simplify passing data between the parent component and a modal. So like in an example above I&#39;m passing {data: 123} to the fooComponent and I wanted to have an option to access this data inside a modal component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*6YWYO4SgsCr-PxOCWP5FXw.png" /><figcaption>it displays {data: ‘123’} - FooComponent.vue</figcaption></figure><p>But what about returning data to the parent from a modal component? My idea, as I mentioned before, was to pass data to resolve() function. I wanted my service to add this.closeModal(data) function to every VueComponent that is passed to a service, so you can access it let’s say this way directly from HTML like this: @click=”closeModal({test:&#39;foo&#39;})&quot;</p><h3>How does it work?</h3><p>At work, I’m using Vuetify that I really love. So, my example works for Vuetify, but it is easy to rewrite it on any other component library.</p><p>First of all, service needs to extend passed component with functions and methods that we will need. Unfortunately, Vue does not have any option to extend a template so I came up with an idea to use a “proxy-parent” component to handle hiding and showing a modal, but also it’s role is to display our fooComponent.</p><p>Extending component object is actually really simple. All you need to do is use Vue.extend() function and pass an object that will be merged with your passed component like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxO4D6eEAq0_74wfp80ptA.png" /></figure><p>Ok great! Our fooComponent now have a closeModal function and some props that we will need later. Now we need to extend the template, and this part of the code is a little dirty and I have a feeling that it can be done in a cleaner way. The first step is to create a temporary component from JS. Our component will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmFkfXCQT6UnS58zGFrn5g.png" /></figure><p>As you can see I’m declaring our extendedModalComponent as a ModalComponent inside of our temporary created component. This part is crucial because it allows us to use our passed component inside the template of our tempComponent like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyVHajpyvOp7MbowGxAOBQ.png" /><figcaption>This template contains some defaults that are not needed</figcaption></figure><p>And the only thing that&#39;s left is to mount our tempComponent to DOM. So to achieve this, we need to create the instance of a component and mount it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*q7GQeeZDrriAGuj0zLrIhQ.png" /></figure><p>So that’s all. I’m also planning to rewrite it in Typescript in the near future. That would allow us to extend our Class-based typescript component with a generic class likeVueModalComponent&lt;T&gt; and the T type could determine the type of passed or returned data.</p><p>And ofc, here is a StackBlitz with a little demo that uses this service.</p><p><a href="https://stackblitz.com/edit/vuetify-services-plugin-demo?file=services%2FModalService.js">https://stackblitz.com/edit/vuetify-services-plugin-demo?file=services%2FModalService.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43b6b2e7057" width="1" height="1" alt=""><hr><p><a href="https://medium.com/js-dojo/how-to-create-a-modal-service-in-vue-js-43b6b2e7057">Vue.js + Typescript best practices #1: Creating modal service that handling dialogs as promise</a> was originally published in <a href="https://medium.com/js-dojo">Vue.js Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>