quarrant / mobx-persist-store

Persist and rehydrate observable properties in mobx store.
268 stars 14 forks source link

Example with functional components? #68

Closed vbylen closed 2 years ago

vbylen commented 2 years ago

Hi,

It seems that all the examples are with class components.

How would you go about getting mobx-persist-store to work with a functional component?

Thank you.

quarrant commented 2 years ago

Hi!

What it https://github.com/quarrant/mobx-persist-store#demo

codeBelt commented 2 years ago

@10000multiplier I think this would work but I never tried it out:

import { observable } from 'mobx';
import { makePersistable } from 'mobx-persist-store';

export const SomeStore = () => {
  const initialState = observable({
    endTime: 0,

    setEndTime(val) {
      this.endTime = val;
    },
  });

  makePersistable(initialState, {
    name: 'SomeStore',
    properties: ['endTime'],
    storage: window.localStorage,
  });

  return initialState;
};

If you use TypeScript I would suggest using classes because you will get better type checking. I did all my stores as functional at one time but now converted them all the classes and I am happier.

vbylen commented 2 years ago

@codeBelt thanks!

Also on an unrelated note, would you recommend integrating this library with mobx-state-tree?

codeBelt commented 2 years ago

Never used mobx-state-tree but let us know how it works.

I have my own way of working with MobX https://github.com/codeBelt/mobx-local-global-stores

quarrant commented 2 years ago

Heh, it's really simple https://codesandbox.io/s/vibrant-frog-iud38?file=/src/App.tsx

vbylen commented 2 years ago

@quarrant wow thanks, just what I needed!

vbylen commented 2 years ago

@quarrant is there also a way to do this with configurePersistable ?

Asking because I'm receiving this error, and it happens with every name I give it image

angelxmoreno commented 2 years ago

@10000multiplier look for all instances of makePersistable and verify you are not reusing the same name prop

angelxmoreno commented 2 years ago

oh wait, you are using react-native. There is some sort of bug that makes hot-reload run certain parts of your code twice. This is not an issue with this lib but hot-reload.

vbylen commented 2 years ago

@angelxmoreno aww okay. Sounds like I don't have to worry about it too much then.

angelxmoreno commented 2 years ago

@10000multiplier follow #64

vbylen commented 2 years ago

@angelxmoreno thanks