Code Monkey home page Code Monkey logo

mobx-cookie's Introduction

logo

mobx-cookie

Synchronises a cookie's value with a MobX observable, allowing observers to react to its changes.

MobX-Cookie is no longer maintained. If you'd like to maintain a fork, please get in contact with me, and I can update this notice to include a link to your project.

Install

npm install mobx-cookie # npm v5+
# or
yarn add mobx-cookie

Example

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

Usage

Import package

import Cookie from 'mobx-cookie'

Instantiate Cookie class

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:

value

Retrieve 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()

License

MIT. See the LICENSE file for more information.

Credits

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.

mobx-cookie's People

Contributors

dependabot-preview[bot] avatar t49tran avatar will-stone avatar zack-rascality avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mobx-cookie's Issues

Not returning expiry bug

In line 106

  _expiresToDateTime(expires) {
    if (typeof expires === 'number') {
      const duration = moment.duration(expires, 'days')
      const ms = duration.asMilliseconds()
      return moment()
        .add(ms, 'ms')
        .format()
    } else {
      moment(expires).format()  /* should return here */
    }
  }

Consider using typescript, that would have picked up this bug quite easily.

`Options` params usage in `constructor` and `set`

Hi @will-stone, thanks for the great work providing a reactive cookie for mobx with mobx-cookie.

Recently, I ran through the code as I need to provide a Typescript definition for this library (we have to use Typescript at work). And there is a minor thing I reckon we can do.

class MobxCookie {
  /**
   * @param {*} name cookie's name
   * @param {*} options (optional) options to send to js-cookie
   */
  constructor(name, options) {
    this.name = name // name of set cookie
    this.options = options // options to send to js-cookie
    this._timeout = null // internal timer

    extendObservable(this, {
      value: jsCookie.get(name) // observable to keep in-sync with cookie value
    })

    this._syncTimeout()
  }

Our constructor is currently accepting a second parameter as js-cookie options. However, I don't think we use this.options anywhere, instead, if someone want to set the option, he/she needs to do it everytime set function is called.

I reckon there are two separated ways we can improve this:

1.) Drop options as the second parameter of the constructor.

2.) set function will make use of this.options if no options param is passed to this function, if there is an options param passed, it will be merged and overriden the class options.

What do you think ? I am happy to submit a PR for this issue.

Cookie is not being saved correctly

Hi guys,
I've been trying to make a login function where a request is send to a Drupal backend and returns the users data + cookie session etc.

Now I have been testing it with Postman, which works just fine. The cookie is stored in the browsers (when i check with dev tools and browser settings). But, whenever I make the same request with axios and using the cookie-mobx library the data it returns is correctly. Then I try to store the cookie, that is visible in the devtools application but not in the browser settings.

What am I missing? I am using the same template-example from mobx-cookie.

How to save JSON in the cookie? Right now I can only save a string in cookie using this library!

import Cookie from 'mobx-cookie';

import User from '../interfaces/User';

type SetUserHandler = (user: User) => void;

interface SessionStore {
  user: User;
  setUser: SetUserHandler;
}

class SessionStoreImpl implements SessionStore {
  cookie = new Cookie("user");

  setUser(user: User) {
    this.cookie.set(user);
  }

  get user() {
    return this.cookie.value;
  }
}

export default SessionStoreImpl;

Not able to set user in cookie, it expects a string

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.