Wonka Wonka - 3 months ago 26
Javascript Question

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
?

Answer

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.

Comments