How to Make localStorage Reactive in Vue

Reactivity is one of Vue’s greatest features. It is also one of the most mysterious if you don’t know what it’s doing behind the scenes. Like, why does it work with objects and arrays and not with other things, like localStorage?

Let’s answer that that question, and while we’re at it, make Vue reactivity work with localStorage.

If we were to run the following code, we would see that the counter being displayed as a static value and not change like we might expect it to because of the interval changing the value in localStorage.

new Vue({
  el: "#counter",
  data: () => ({
    counter: localStorage.getItem("counter")
  }),
  computed: {
    even() {
      return this.counter % 2 == 0;
    }
  },
  template: `<div>
    <div>Counter: {{ counter }}</div>
    <div>Counter is {{ even ? 'even' : 'odd' }}</div>
  </div>`
});
// some-other-file.js
setInterval(() => {
  const counter = localStorage.getItem("counter");
  localStorage.setItem("counter", +counter + 1);
}, 1000);

While the counter property inside the Vue instance is reactive, it won’t change just because we changed its origin in localStorage

There are multiple solutions for this, the nicest perhaps is using Vuex and keep the store value in sync with localStorage. But what if we need something simple like what we have in this example? We have to take a dive in how Vue’s reactivity system works.

Reactivity in Vue

When Vue initializes a component instance, it observes the data option. This means it walks through all of the properties in data and converts them to getters/setters using Object.defineProperty. By having a custom setter for each property, Vue knows when a property changes, and it can notify the dependents that need to react to the change. How does it know which dependents rely on a property? By tapping into the getters, it can register when a computed property, watcher function, or  render function accesses a data prop.

// core/instance/state.js
function initData () {
  // ...
  observe(data)
}
// core/observer/index.js
export function observe (value) {
  // ...
  new Observer(value)
  // ...
}

export class Observer {
  // ...
  constructor (value) {
    // ...
    this.walk(value)
  }
  
  walk (obj) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }
} 


export function defineReactive (obj, key, ...) {
  const dep = new Dep()
  // ...
  Object.defineProperty(obj, key, {
    // ...
    get() {
      // ...
      dep.depend()
      // ...
    },
    set(newVal) {
      // ...
      dep.notify()
    }
  })
}

So, why isn’t localStorage reactive? Because it’s not an object with properties.

But wait. We can’t define getters and setters with arrays either, yet arrays in Vue are still reactive. That’s because arrays are a special case in Vue. In order to have reactive arrays, Vue overrides array methods behind the scenes and patches them together with Vue’s reactivity system.

Could we do something similar with localStorage?

Overriding localStorage functions

As a first try, we can fix our initial example by overriding localStorage methods to keep track which component instances requested a localStorage item.

// A map between localStorage item keys and a list of Vue instances that depend on it
const storeItemSubscribers = {};


const getItem = window.localStorage.getItem;
localStorage.getItem = (key, target) => {
  console.info("Getting", key);


  // Collect dependent Vue instance
  if (!storeItemSubscribers[key]) storeItemSubscribers[key] = [];
  if (target) storeItemSubscribers[key].push(target);


  // Call the original function 
  return getItem.call(localStorage, key);
};


const setItem = window.localStorage.setItem;
localStorage.setItem = (key, value) => {
  console.info("Setting", key, value);


  // Update the value in the dependent Vue instances
  if (storeItemSubscribers[key]) {
    storeItemSubscribers[key].forEach((dep) => {
      if (dep.hasOwnProperty(key)) dep[key] = value;
    });
  }


  // Call the original function
  setItem.call(localStorage, key, value);
};
new Vue({
  el: "#counter",
  data: function() {
    return {
      counter: localStorage.getItem("counter", this) // We need to pass 'this' for now
    }
  },
  computed: {
    even() {
      return this.counter % 2 == 0;
    }
  },
  template: `<div>
    <div>Counter: {{ counter }}</div>
    <div>Counter is {{ even ? 'even' : 'odd' }}</div>
  </div>`
});
setInterval(() => {
  const counter = localStorage.getItem("counter");
  localStorage.setItem("counter", +counter + 1);
}, 1000);

In this example, we redefine getItem and setItem in order to collect and and notify the components that depend on localStorage items. In the new getItem, we note which component requests which item, and in setItems, we reach out to all the components that requested the item and rewrite their data prop.

In order to make the code above work, we have to pass on a reference to the component instance to getItem and that changes its function signature. We also can’t use the arrow function anymore because we otherwise wouldn’t have the correct this value.

If we want to do better, we have to dig deeper. For example, how could we keep track of dependents without explicitly passing them on?

How Vue collects dependencies

For inspiration, we can go back to Vue’s reactivity system. We previously saw that a data property’s getter will subscribe the caller to the further changes of the property when the data property is accessed. But how does it know who made the call? When we get a data prop, its getter function doesn’t have any input regarding who the caller was. Getter functions have no inputs. How does it know who to register as a dependent? 

Each data property maintains a list of its dependents that need to react in a Dep class. If we dig deeper in this class, we can see that the dependent itself is already defined in a static target variable whenever it is registered. This target is set by a so-far-mysterious Watcher class. In fact, when a data property changes, these watchers will be actually notified, and they will initiate the re-rendering of the component or the recalculation of a computed property.

But, again, who they are?

When Vue makes the data option observable, it also creates watchers for each computed property function, as well as all the watch functions (which shouldn’t be confused with the Watcher class), and the render function of every component instance. Watchers are like companions for these functions. They mainly do two things:

  1. They evaluate the function when they are created. This triggers the collection of dependencies.
  2. They re-run their function when they are notified that a value they rely on has changed. This will ultimately recalculate a computed property or re-render a whole component.

There is an important step that happens before watchers call the function they are responsible for: they set themselves as target in a static variable in the Dep class. This makes sure the they are registered as dependent when a reactive data property is accessed.

Keeping track of who called localStorage

We can’t exactly do that because we don’t have access to the inner mechanics of Vue. However, we can use the idea from Vue that lets a watcher set the target in a static property before it calls the function it is responsible for. Could we set a reference to the component instance before localStorage gets called?

If we assume that localStorage gets called while setting the data option, then we can hook into beforeCreate and created. These two hooks get triggered before and after initializing the data option, so we can set, then clear, a target variable with a reference to the current component instance (which we have access to in lifecycle hooks). Then, in our custom getters, we can register this target as a dependent.

The final bit we have to do is make these lifecycle hooks part of all our components. We can do that with a global mixin for the whole project.

// A map between localStorage item keys and a list of Vue instances that depend on it
const storeItemSubscribers = {};

// The Vue instance that is currently being initialised
let target = undefined;

const getItem = window.localStorage.getItem;
localStorage.getItem = (key) => {
  console.info("Getting", key);

  // Collect dependent Vue instance
  if (!storeItemSubscribers[key]) storeItemSubscribers[key] = [];
  if (target) storeItemSubscribers[key].push(target);

  // Call the original function
  return getItem.call(localStorage, key);
};

const setItem = window.localStorage.setItem;
localStorage.setItem = (key, value) => {
  console.info("Setting", key, value);

  // Update the value in the dependent Vue instances
  if (storeItemSubscribers[key]) {
    storeItemSubscribers[key].forEach((dep) => {
      if (dep.hasOwnProperty(key)) dep[key] = value;
    });
  }
  
  // Call the original function
  setItem.call(localStorage, key, value);
};

Vue.mixin({
  beforeCreate() {
    console.log("beforeCreate", this._uid);
    target = this;
  },
  created() {
    console.log("created", this._uid);
    target = undefined;
  }
});

Now, when we run our initial example, we will get a counter that increases the number every second.

new Vue({
  el: "#counter",
  data: () => ({
    counter: localStorage.getItem("counter")
  }),
  computed: {
    even() {
      return this.counter % 2 == 0;
    }
  },
  template: `<div class="component">
    <div>Counter: {{ counter }}</div>
    <div>Counter is {{ even ? 'even' : 'odd' }}</div>
  </div>`
});
setInterval(() => {
  const counter = localStorage.getItem("counter");
  localStorage.setItem("counter", +counter + 1);
}, 1000);

The end of our thought experiment

While we solved our initial problem, keep in mind that this is mostly a thought experiment. It lacks several features, like handling removed items and unmounted component instances. It also comes with restrictions, like the property name of the component instance requires the same name as the item stored in localStorage. That said, the primary goal is to get a better idea of how Vue reactivity works behind the scenes and get the most out of it, so that’s what I hope you get out of all this.

The post How to Make localStorage Reactive in Vue appeared first on CSS-Tricks.

How the Vue Composition API Replaces Vue Mixins

Looking to share code between your Vue components? If you’re familiar with Vue 2, you’ve probably used a mixin for this purpose. But the new Composition API, which is available now as a plugin for Vue 2 and an upcoming feature of Vue 3, provides a much better solution.

In this article, we’ll take a look at the drawbacks of mixins and see how the Composition API overcomes them and allows Vue applications to be far more scalable.

Mixins in a nutshell

Let’s quickly review the mixins pattern as it’s important to have it top-of-mind for what we’ll cover in the next sections.

Normally, a Vue component is defined by a JavaScript object with various properties representing the functionality we need — things like data, methods, computed, and so on.

// MyComponent.js
export default {
  data: () => ({
    myDataProperty: null
  }),
  methods: {
    myMethod () { ... }
  }
  // ...
}

When we want to share the same properties between components, we can extract the common properties into a separate module:

// MyMixin.js
export default {
  data: () => ({
    mySharedDataProperty: null
  }),
  methods: {
    mySharedMethod () { ... }
  }
}

Now we can add this mixin to any consuming component by assigning it to the mixin config property. At runtime, Vue will merge the properties of the component with any added mixins.

// ConsumingComponent.js
import MyMixin from "./MyMixin.js";


export default {
  mixins: [MyMixin],
  data: () => ({
    myLocalDataProperty: null
  }),
  methods: {
    myLocalMethod () { ... }
  }
}

For this specific example, the component definition used at runtime would look like this:

export default {
  data: () => ({
    mySharedDataProperty: null
    myLocalDataProperty: null
  }),
  methods: {
    mySharedMethod () { ... },
    myLocalMethod () { ... }
  }
}

Mixins are considered “harmful”

Back in mid-2016, Dan Abramov wrote “Mixins Considered Harmful” in which he argues that using mixins for reusing logic in React components is an anti-pattern, advocating instead to move away from them.

The same drawbacks he mentions about React mixins are, unfortunately, applicable to Vue as well. Let’s get familiar with these drawbacks before we take a look at how the Composition API overcomes them.

Naming collisions

We saw how the mixin pattern merges two objects at runtime. What happens if they both share a property with the same name?

const mixin = {
  data: () => ({
    myProp: null
  })
}


export default {
  mixins: [mixin],
  data: () => ({
    // same name!
    myProp: null
  })
}

This is where the merge strategy comes into play. This is the set of rules to determine what happens when a component contains multiple options with the same name.

The default (but optionally configurable) merge strategy for Vue components dictates that local options will override mixin options. There are exceptions though. For example, if we have multiple lifecycle hooks of the same type, these will be added to an array of hooks and all will be called sequentially.

Even though we shouldn’t run into any actual errors, it becomes increasingly difficult to write code when juggling named properties across multiple components and mixins. It’s especially difficult once third-party mixins are added as npm packages with their own named properties that might cause conflicts.

Implicit dependencies

There is no hierarchical relationship between a mixin and a component that consumes it. This means that a component can use a data property defined in the mixin (e.g. mySharedDataProperty) but a mixin can also use a data property it assumes is defined in the component (e.g. myLocalDataProperty). This is commonly the case when a mixin is used to share input validation. The mixin might expect a component to have an input value which it would use in its own validate method.

This can cause problems, though. What happens if we want to refactor a component later and change the name of a variable that the mixin needs? We won’t notice, looking at the component, that anything is wrong. A linter won’t pick it up either. We’ll only see the error at runtime.

Now imagine a component with a whole bunch of mixins. Can we refactor a local data property, or will it break a mixin? Which mixin? We’d have to manually search them all to know.

Migrating from mixins

Dan’s article offers alternatives to mixins, including higher-order components, utility methods, and some other component composition patterns.

While Vue is similar to React in many ways, the alternative patterns he suggests don’t translate well to Vue. So, despite this article being written in mid-2016, Vue developers have been suffering with mixin issues ever since.

Until now. The drawbacks of mixins were one of the main motivating factors behind the Composition API. Let’s get a quick overview of how it works before we look at how it overcomes the issues with mixins.

Composition API crash course

The key idea of the Composition API is that, rather than defining a component’s functionality (e.g. state, methods, computed properties, etc.) as object properties, we define them as JavaScript variables that get returned from a new setup function.

Take this classic example of a Vue 2 component that defines a “counter” feature:

//Counter.vue
export default {
  data: () => ({
    count: 0
  }),
  methods: {
    increment() {
      this.count++;
    }
  },
  computed: {
    double () {
      return this.count * 2;
    }
  }
}

What follows is the exact same component defined using the Composition API.

// Counter.vue
import { ref, computed } from "vue";


export default {
  setup() {
    const count = ref(0);
    const double = computed(() => count * 2)
    function increment() {
      count.value++;
    }
    return {
      count,
      double,
      increment
    }
  }
}

You’ll first notice we import a ref function, which allows us to define a reactive variable that functions pretty much the same as a data variable. Same story for the computed function.

The increment method is not reactive so it can be declared as a plain JavaScript function. Notice that we need to change the sub-property value in order to change the value of the count reactive variable. That’s because reactive variables created using ref need to be objects to retain their reactivity as they’re passed around.

It’s a good idea to consult the the Vue Composition API docs for a detailed explanation of how ref works.

Once we’ve defined these features, we return them from the setup function. There is no difference in functionality between the two components above. All we did was use the alternative API.

Tip: the Composition API will be a core feature of Vue 3, but you can also use it in Vue 2 with the NPM plugin @vue/composition-api.

Code extraction

The first clear advantage of the Composition API is that it’s easy to extract logic.

Let’s refactor the component defined above with the Composition API so that the features we defined are in a JavaScript module useCounter. (Prefixing a feature’s description with “use” is a Composition API naming convention.)

//useCounter.js
import { ref, computed } from "vue";


export default function () {
  const count = ref(0);
  const double = computed(() => count * 2)
  function increment() {
    count.value++;
  }
  return {
    count,
    double,
    increment
  }
}

Code reuse

To consume that feature in a component, we simply import the module into the component file and call it (noting that the import is a function). This returns the variables we defined, and we can subsequently return these from the setup function.

// MyComponent.js
import useCounter from "./useCounter.js";

export default {
  setup() {
    const { count, double, increment } = useCounter();
    return {
      count,
      double,
      increment
    }
  }
}

This may all seem a bit verbose and pointless at first, but let’s see how this pattern overcomes the issues with mixins we looked at earlier.

Naming collisions… solved!

We saw before how a mixin can use properties that may have the same name as those in the consuming component, or even more insidiously, in other mixins used by the consuming component.

This is not an issue with the Composition API because we need to explicitly name any state or methods returned from a composition function:

export default {
  setup () {
    const { someVar1, someMethod1 } = useCompFunction1();
    const { someVar2, someMethod2 } = useCompFunction2();
    return {
      someVar1,
      someMethod1,
      someVar2,
      someMethod2
    }
  }
}

Naming collisions will be resolved the same way they are for any other JavaScript variable.

Implicit dependencies… solved!

We also saw before how a mixin may use data properties defined on the consuming component, which can make the code fragile and very hard to reason about.

A composition function can also call on a local variable defined in the consuming component. The difference, though, is that this variable must now be explicitly passed to the composition function.

import useCompFunction from "./useCompFunction";


export default {
  setup () {
    // some local value the a composition function needs to use
    const myLocalVal = ref(0);


    // it must be explicitly passed as an argument
    const { ... } = useCompFunction(myLocalVal);
  }
}

Wrapping up

The mixin pattern looks pretty safe on the surface. However, sharing code by merging objects becomes an anti-pattern due to the fragility it adds to code and the way it obscures the ability to reason about the functionality.

The most clever part of the Composition API is that it allows Vue to lean on the safeguards built into native JavaScript in order to share code, like passing variables to functions, and the module system.

Does that mean the Composition API is superior in every way to Vue’s classic API? No. In most cases you’ll be fine to stick with the classic API. But if you’re planning to reuse code, the Composition API is unquestionably superior.

The post How the Vue Composition API Replaces Vue Mixins appeared first on CSS-Tricks.