
Security News
The Changelog Podcast: Practical Steps to Stay Safe on npm
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.
mobx-cookie
Advanced tools
Syncs a cookie's value with a MobX observable, allowing observers to react to its changes.
Synchronises a cookie's value with a MobX observable, allowing observers to react to its changes.
npm install mobx-cookie # npm v5+
# or
yarn add mobx-cookie
import { action, computed, makeObservable, observable } from 'mobx'
import Cookie from 'mobx-cookie'
class Store {
cookie = new Cookie('thing')
constructor() {
makeObservable(this, {
cookie: observable,
timestamp: computed,
setTimestamp: action,
unsetTimestamp: action,
})
}
get thing() {
return this.cookie.value
}
setThing = (value) => {
this.cookie.set(value, { expires: 2 }) // 2 day expiry
}
unsetThing = () => {
this.cookie.remove()
}
}
const store = new Store()
// console: undefined
store.setThing('testing')
// console: "testing"
store.unsetThing()
// console: undefined
import Cookie from 'mobx-cookie'
Initialise and set the key name of the cookie
new Cookie(name)
e.g.
@observable cookie = new Cookie('name of cookie in browser')
// or
cookie = new Cookie('name of cookie in browser')
// and decorate
decorate(Store, {
cookie: observable,
})
The observable now has the following methods:
valueRetrieve the value of the cookie stored in this observable
this.cookie.value // when cookie is updated, this will update too.
set(value[, options])Set the value assigned to the observed cookie
this.cookie.set('value')
mobx-cookie is essentially a wrapper around the js-cookie package. Any options set as the second argument (as an object) will be passed to js-cookie.
e.g.
this.cookie.set('value', { expires: 2 }) // sets cookie to expire in two days.
remove()Removes the cookie from the browser and sets the observable to undefined
this.cookie.remove()
MIT. See the LICENSE file for more information.
Thanks go to the creators of the dependency, js-cookie, and of course to Michel Weststrate for MobX.
The logo is comprised of MobX's official logo's background by osenvosem and a cookie icon from icons8.
FAQs
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.

Security News
Experts push back on new claims about AI-driven ransomware, warning that hype and sponsored research are distorting how the threat is understood.

Security News
Ruby's creator Matz assumes control of RubyGems and Bundler repositories while former maintainers agree to step back and transfer all rights to end the dispute.