问题
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.
I came across the new mobx-utils
fromPromise
which I think would get the author
value if it exists in local storage, and wait for AsyncStorage
to assign it to the author
observable, so it can be called from another store without being null
.
I tried using fromPromise
first in the AuthorStore
to log the author
value, but it shows as Got undefined
in console, and the usual null
error in the BookStore
when it comes to the AuthorStore.author
part.
UPDATE:
class AuthorStore {
@observable author = null;
@computed get theAuthor() {
authorPromise = fromPromise(AsyncStorage.getItem('author').then(data => JSON.parse(data)));
// combine with when..
when(
() => authorPromise.state !== "pending",
() => {
console.log("Got Author", authorPromise.reason || authorPromise.value) // This runs, and returns author
console.log("Got Name", authorPromise.reason || authorPromise.value.name) // This runs, and returns name
return authorPromise.value; // This doesn't get returned in BookStore when calling this computed
}
);
}
}
class BookStore {
@observable book = {
authorName: AuthorStore.theAuthor.name, // doesn't get computed returned value from promise
bookTitle: null
}
}
How can I get the fromPromise
value assigned by the AuthorStore
computed function theAuthor
to return the promised authorPromise
value into BookStore
under authorName
?
回答1:
FromPromise creates a new object wrapping the original promise. So your authorFromStorage
is just a normal promise in your example, not having a state
property at all. So you should change your code to:
authorPromise = fromPromise(AsyncStorage.getItem('author').then(data => JSON.parse(data)))
And then when(() => authorPromise.state !== "pending")
etc..
** UPDATE **
class AuthorStore {
@observable author = null;
constructor() {
AsyncStorage.getItem('author').then(data => { this.author = JSON.parse(data) });
}
}
class BookStore {
@observable book = {
authorName: function() { // a function in an observable creates a computed prop
return AuthorStore.author && AuthorStore.author.name
},
bookTitle: null
}
}
来源:https://stackoverflow.com/questions/39103568/mobx-observable-value-promised-in-a-store-constructor-using-frompromise-stays