DEV Community

Esteban Hernández
Esteban Hernández

Posted on

Reactive Cookies with RxJs

We need to store data on the client's device securely and, for that, we have cookies. The NPM package js-cookie provides us with a simple interface to store and retrieve cookies. Let's build a wrapper for this interface to make our cookies reactive.

A reactive cookie will be created with a key.

import { of, Subject } from 'rxjs';

class ReactiveCookie {

    constructor(key) {
        this.key = key;
    }

}

Let's add getters and setters for the value.

constructor() {
    ...
    this.value = new Subject();
}

getValue() {
    return this.value;
}

setValue(value) {
    this.value.next(value);
}

Great! We want the stored cookie to be updated every time we set the value so that it's always in sync. We'll subscribe to the value subject and set the cookie on each value.

constructor() {
    ...
    this.synchronize();
}

synchronize() {
    this.getValue().subscribe((value) => { Cookies.set(this.key, value); });
}

Alright, what about when there is already a stored value. We want this stored value to be set as the initial value so we'll add that as well to the constructor.

constructor() {
    this.retrieveStoredValue();
}

getStoredValue() {
    return of(Cookies.get(this.key));
}

retrieveStoredValue() {
    this.getStoredValue().subscribe((value) => { this.value.next(value) });
}

Woo! Now, whenever we create a Cookie with a key that already has a value stored, that value will automatically be loaded into the ReactiveCookie value. Furthermore, setting a new value will immediately update the value of the stored cookie. Finally, lets add clear() and remove() methods to complete our functionality.

clear() {
    this.setValue(null);
}

remove() {
    Cookies.delete(this.key);
    this.value.complete();
}

Now, go out and store some values!

Top comments (0)