Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MobX - Run constructor of one store in another?

So I have 2 stores, an AuthorStore:

class AuthorStore {
  constructor() {
      // has author.name and is always present in storage
      AsyncStorage.getItem('author').then(action((data) => {
        this.author = JSON.parse(data);
      }));
  }

  @observable author = null;
}

and a BookStore:

import AuthorStore from 'authorStore';
class BookStore {
  @observable book = {
    authorName: AuthorStore.author.name,
    bookTitle: null
  }
}

I keep getting an error in BookStore that it cannot get property of null, as if the AuthorStore.author.name is null. So it's reading the default author value from the AuthorStore without the constructor running first to assign it the value.

How can I get the value assigned by the AuthorStore constructor to author in the BookStore?

like image 971
Wonka Avatar asked Oct 23 '25 15:10

Wonka


1 Answers

You could store a reference to the getItem('author')-promise, and make sure it is fulfilled before you do anything in the bookstore:

// authorStore.js
class AuthorStore {
  @observable author = null;
  getAuthorPromise = null;

  constructor() {
    this.getAuthorPromise = AsyncStorage.getItem('author').then(action((data) => {
      this.author = JSON.parse(data);
    }));
  }
}

export default new AuthorStore();

// bookStore.js
class BookStore {
  @observable book = null;

  constructor() {
    authorStore.getAuthorPromise.then(action(() => 
      this.book = {
        authorName: authorStore.author.name,
        bookTitle: null
      };
    ));
  }
}

You could also get the author before you create any stores and give the author to the AuthorStore constructor, so you can create your BookStore synchronously:

// AuthorStore.js
class AuthorStore {
  @observable author = null;

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

export default AuthorStore;

// BookStore.js
class BookStore {
  @observable book = null;
  authorStore = null;

  constructor(authorStore) {
    this.authorStore = authorStore;
    this.book = {
      authorName: authorStore.author.name,
      bookTitle: null
    };
  }
}

export default BookStore;

// app.js
import AuthorStore from './AuthorStore';
import BookStore from './BookStore';

AsyncStorage.getItem('author').then(data => {
  const author = JSON.parse(data);
  const authorStore = new AuthorStore(author);
  const bookStore = new BookStore(authorStore);
}));

Keep in mind that there are a lot of ways to do it.

like image 103
Tholle Avatar answered Oct 25 '25 03:10

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!