Illegal constructor error with mobx reaction - mobx

I have the following code
this.disposer = reaction(
() => this.store.show,
this._handle
);
private _handle = async () => {
if (this._document) {
this._close();
} else {
await this._open();
}
};
I get the following error "Illegal constructor" on line "await this._open();"
Does anyone know why?

Related

promise returned from getRestaurantsFromYelp is ignored

Morning/Evening everybody
So I'm tryna get restaurants from yelpApi(react native App), but the fetch is not working.
First I'm getting a message as what "businesses" isn't a resolved variable, and the response from my getRestaurantsFromYelp() function is getting ignored, don't know why. If anybody could hep me fix that.
const [restaurantsData, setRestaurantsData] = useState(localRestaurants);
const getRestaurantsFromYelp = () => {
const yelpUrl = "api.yelp.com/v3/businesses/search?term=restaurants&location=US"
const apiOptions = {
headers : {
Authorization : `Bearer ${YELP_API_KEY}`,
}
}
return fetch(yelpUrl, apiOptions).then((res) => res.json()).then((json) => setRestaurantsData(json.businesses)); //message => unresolved variable businesses
};
useEffect(() =>{
getRestaurantsFromYelp(); // message => promise returned from getRestaurantsFromYelp is ignored
}, [])

WatermelonDB - Error when performing batch insertion

I have a single table created on WatermelonDB, in my React Native Android app. When I use batch to insert new records to the table, from a component, I get the error TypeError: Cannot read property 'id' of undefined thrown inside batch.
This is where batch is called with a list of Promise objects:
await database.action(async () => {
const allRecords = this.prepareInsertion(smsTransaction, records);
await database.batch(...allRecords);
console.log(allRecords.length);
});
prepareInsertion(smsTransaction, messages) {
return messages.map(async message => {
try {
return smsTransaction.prepareCreate(transaction => {
const parsedFields = parseFields(message);
transaction.type = parsedFields.type;
transaction.read_at = parsedFields.read_at;
});
} catch (e) {
console.log(e);
}
});
}
Issue was with the async keyword.
return messages.map(message => {
Models to be passed to database.batch, not Promises.

Error handling in Vue JS - errors not caught

I have the following code:
fooService.update(this.bar).then( this.$emit('updated', this.updatedBar),).catch(err => {...
If an error is encountered, then the error is not caught. If I change the code to be:
fooService.update(this.bar).then(x => {this.$emit('updated', this.updatedBar);}).catch(err => {...
Then the error is caught and shows as expected. Can anyone explain to me what is going on and why it behaves in that way?
Edit
Underlying service code:
function updateBar(bar) {
return $http.put(`/api/bar/${bar.Id}`, bar);
}
So I still think the error is happening in the this.$emit the reason why, in
fooService.update(this.bar).then( this.$emit('updated', this.updatedBar),).catch(err => {
It has to evaluate the this.$emit first as you're setting the response from that function as the .then and not the call itself.
Proof of it doing that
function emit(){
console.log('emit')
}
var promise = new Promise(function(resolve,reject){
setTimeout(() => {
console.log('promise is done')
reject();
}, 1000)
})
promise.then(emit()).catch( function() {console.log('carry on');})
notice how it logs "emit" first
Now if that errors you can see it doesn't hit the catch
function emit(){
console.log('emit')
throw new Error("bad")
}
var promise = new Promise(function(resolve,reject){
setTimeout(() => {
console.log('promise is done')
reject();
}, 1000)
})
promise.then(emit()).catch( function() {console.log('carry on');})
So under the hood it's doing this (the simplest way I can think of)
emit()
try{
getService()
} catch{
...
}
Whereas if you actually pass the .then a function it changes the order of things
function emit(){
console.log('emit')
throw new Error("bad")
}
var promise = new Promise(function(resolve,reject){
setTimeout(() => {
console.log('promise is done')
reject();
}, 1000)
})
promise.then(() => {emit()}).catch( function() {console.log('carry on');})
and again under the hood it looks like this
try{
getService()
emit()
} catch{
...
}

Failed in retrieve data from AsyncStorage

I am a beginner at react-native.
I trying to retrieve data that stored from screen1.js in Screen2.js but I failed.
I have import Asyncstorage from react-native for both .js
This how I store variable from screenone.js :
class screenone extends Component {
state = {
oldpin: '000000',
newpin: '',
secpin: '',
};
onPressButton = () => {
if (this.state.newpin == this.state.secpin) {
this.setState(
{ oldpin: this.state.newpin },
async() => await this.storeData());
}
else {
ToastAndroid.show("Password Unmatched", ToastAndroid.SHORT);
}
}
storeData = async () =>{
const {oldpin} = this.state;
let pin : oldpin;
try{
await AsyncStorage.setItem('mypin',pin);
ToastAndroid.show("Password Changed", ToastAndroid.SHORT);
}
catch (err){
console.warn(err)
}}
....
This is how I trying to retrieve data in screentwo.js:
class screentwo extends Component {
constructor(props) {
super(props);
this.onComplete = this.onComplete.bind(this);
this.state = {
pin: ''
};
}
retrieveData = async (mypin) => {
try {
let value = await AsyncStorage.getItem(mypin);
if (value !== null) {
console.log(value);
this.setState({
pin: value})
}
} catch (error) {
console.warn(err)
}
}
onComplete(inputtedPin, clear) {
retrieveData();
if (inputtedPin !== this.state.pin) {
ToastAndroid.show("Incorrect Pin", ToastAndroid.SHORT);
clear();
} else {
ToastAndroid.show("Pin is correct", ToastAndroid.SHORT);
clear();
this.props.navigation.navigate("Dashboard");
}}
....
Error:
Reference Error: ReferenceError:Can't find variable:retrieveData
Am I using the right way to stored and retrieve data?
Any suggestion?
Thank you.
There are a couple of issues that I can see with your code.
Firstly the retrieveData() function. It is asynchronous and should be called with await also you are getting the error: Reference Error: ReferenceError:Can't find variable:retrieveData because you haven't used this
So ideally you should call it await this.retrieveData();
There are a few more issues with this function. You use the parameter mypin but don't seem to pass any parameter to the function when you call it. Fixing this issue you should call retreiveData() like this:
await this.retrieveData('mypin');
Or you could remove passing the paramater altogether, which I will show how to do in my refactor below.
Finally you call retreiveData every time you check the inputtedPin this isn't that efficient, it is asynchronous so it may take some time, and secondly it also takes time for the setState function to complete, which means that the state may not have updated in time when you go to check it against the inputtedPin, meaning that you are checking the inputtedPin against the wrong value.
Code Refactor
This is how I would refactor your component.
Refactor retrieveData so that it no longer takes a parameter and the key is hardcoded in the .getItem
In the componentDidMount get the value of the pin from AsyncStorage and save it to state.
Remove the retrieveData call from onComplete
Here is the refactor
retrieveData = async () => { // parameter have been removed
try {
let value = await AsyncStorage.getItem('mypin'); // notice I am now passing the key as a string not as a parameter
if (value !== null) {
console.log(value);
this.setState({ pin: value })
}
} catch (error) {
console.warn(err)
}
}
// here we call the refactored retrievedData which will set the state.
async componentDidMount () {
await this.retrieveData();
}
onComplete(inputtedPin, clear) {
// we remove the call to retrieveData as we have already gotten the pin in the componentDidMount
if (inputtedPin !== this.state.pin) {
ToastAndroid.show("Incorrect Pin", ToastAndroid.SHORT);
clear();
} else {
ToastAndroid.show("Pin is correct", ToastAndroid.SHORT);
clear();
this.props.navigation.navigate("Dashboard");
}
}
only replace
retrieveData();
to
this.retrieveData();
When you call async method from a caller method that method also become async Try prefix
async onComplete () { await this.retrieveData() }

Unable to get async/await working in react native

I have not been able to get async/await working in a react native project.
const async getUser = () => {
try{
let value = await AsyncStorage.getItem("user");
return value;
}
catch(e){
throw e
}
}
I always get an Unexpected token error. I have tried adding { "presets": ["react-native", "es2015", "babel-preset-stage-3"] } with the same result.
On version ^0.35.0
The syntax for async arrow functions is:
const getUser = async () => {
...
}