React-native and Firebase: Wait for Firebase data

I am currently implementing an application which relies on Firebase data before it can continue. However, I often (unless I deliberately wait) get the result Cannot read property [property] of null. I very much suspect that this is because the firebase request could not be made before I call this object.

Now I am looking for methods to implement a rendez-vous, or a barrier, really anything that implements a checkpoint where all firebase data are received, before it continues. Is there anything in Javascript which helps me to do so, or any library, or any react-native library that helps me to achieve this?

My code looks as follows: (Fb is the firebase interface)

@action
  bookInterestedBike() {
    this.bookedBikeNo = this.interestBikeNo;
    this.downloadBikeObj();
    this.updateBikeDataStartRide();
    this.updateUserDataStartRide();
    //
    //This is where the firebase checkpoint / barrier should happen, and no progress should be made unless this data was fetched!
    //
    this.startTimer();
  }

@action
  downloadBikeObj() {
    Fb.staticBikes.child(String(this.bookedBikeNo)).once('value', (bikeObj) => {
      this.bikeObj = bikeObj.val();
      console.log("Save object is: ");
      console.log(this.bikeObj);
    });
  }

  updateBikeDataStartRide() {
    var updateVals = {}
    updateVals[this.interestBikeNo] = {
      bike_no: this.interestBikeNo,
      current_user: "self",
      positionLat: this.usrLat,
      positionLng: this.usrLng
    };
    Fb.bikes.update(updateVals);
    return false;
  };

  updateUserDataStartRide() {
    var updateVals = {}
    updateVals[this.uuid] = {
      bike_no: this.bookedBikeNo,
      uuid: this.uuid //TODO: remove this in deployment
    };
    Fb.users.update(updateVals);
    return false;
  };


Source: stackoverflow-javascript

React Native – async/await does not work

Is it possible to use async/await outside of classes?
For example I use AsyncStorage to store access token and want to get this token before StackNavigator will be initialized.

container.js

import React from 'react';
import { StackNavigator } from 'react-navigation';
import PairingView from '../components/PairingView';
import MainView from '../components/MainView';
import { getTokenFromStorageAsync } from '../helpers/asyncStorageHelper';

const accessToken = getTokenFromStorageAsync().done();
console.log(accessToken);   <---------- undefined

const AppNavigator = StackNavigator({
  PairingRoute: {
    screen: PairingView
  },
  MainRoute: {
    screen: MainView
  }
}, {
  initialRouteName: (accessToken == null) ? 'PairingRoute' : 'MainRoute',
  initialRouteParams: {
    token: accessToken
  }
});

const App = () => (
  <AppNavigator />
);

export default App;

asyncStorageHelper.js

import { AsyncStorage } from 'react-native';

export const getTokenFromStorageAsync = async () => {
  try {
    const value = await AsyncStorage.getItem('@nfs:token');
    console.log(value);   <---------- access token
    if (value != null)
      return value;
  } catch (err) {
    console.error(err);
  }
  return undefined;
};


Source: stackoverflow-javascript

Can’t find variable: navigate

I am trying to navigate between two screen with the help of react-navigation. I am able to access navigate inside the render method as its scope is also inside that method.

Where should I declare so I can access it any method of this component. I am trying to access navigate inside the onPressButton method but it giving an error.

Can’t find variable: navigate

import React, { Component } from "react";
import { View, Text, Image, Button, Alert, StyleSheet } from "react-native";
import styles from "./Styles";
import * as strings from "./Strings";
import RoundButton from "./RoundButton";
var DialogAndroid = require("react-native-dialogs");
import { StackNavigator } from "react-navigation";

export default class CreateMessageScreen extends Component {
  render() {  
    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>
        <Image source={require("./img/create_message.png")} />
        <Text style={styles.textStyle}>{strings.create_message}</Text>

        <RoundButton
          textStyle={styles.roundTextStyle}
          buttonStyle={styles.roundButtonStyle}
          onPress={this.onPressButton}
        >
          CREATE MESSAGE
        </RoundButton>

      </View>
    );
  }

  onPressButton() {
    var options = {
      title: strings.app_name,
      content: strings.create_message,
      positiveText: strings.OK,
      onPositive: () => navigate("DashboardScreen")
    };
    var dialog = new DialogAndroid();
    dialog.set(options);
    dialog.show();
  }
}


Source: stackoverflow-javascript

Objects are not valid as a React child (found: object with keys {…})

I’m trying to fetch some example data and display some text in my react native app. This is how the code looks (pretty much taken straight from the tutorial):

function getExampleData() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies[0].title;
    })
    .catch((error) => {
      console.log(error);
      return 'Error!';
    });
}

class CenterView extends React.Component {
  render() {
    return (
      <Text>{getExampleData()}</Text>
    );
  }
}

The response body from the url:

{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

I’m getting the error message

enter image description here

If I put toString() after the function call, [object Object] is printed out, so I guess it’s a matter of turning the object into text before returning. Can anyone tell me how this is done?


Source: stackoverflow-javascript

React Native – populating ListView with async data

I’m getting a list of items as a prop through the redux store. This prop is asyncronous.

My ListView works with syncronous hardcoded data. So the problem is populating with the prop when I actually receive it.

I’m making a ListView out of this item prop data. What’s the best practice on life cycle choices to setState with this prop? I’ve tried componentDidMount – but that’s too early and only called once. I tried componentWillReceiveprops – but that’s also too early since other props get there first. I also tried componentWillUpdate and no luck. I’m tempted to put it in the render function because I know I can grab that prop when I get it but that makes the render function no longer pure.

Thanks for any help!

this.setState({
  dataSource: this.state.dataSource.cloneWithRows(this.props.items);
})


Source: stackoverflow-javascript

How to correctly overflowing / layering of views in react-native?

I am trying to figure out appropriate way to approach things like custom modals in react-native, i.e. overlay a view on top of another.

Additionally handle views that go of screen, do I need to set overflow hidden on parent view for this, should I use negative margins / absolute positioning or translate etc?

I saw some sources online explaining how to achieve these in various ways i.e. absolute positioning and z-indez or something called elevate, so I am not sure which of these is preferred? is it a good idea to use fixed positioning perhaps? And do parent views need their position to be set to relative?


Source: stackoverflow-javascript

Can only set property values within a transaction

I encountered a error when I want to change a value in a class.These are codes.I found tempDateSource.MonStarNum = tempDateSource.MonStarNum + 1; error when I debug it.

setStarNumInDataSource(i){
    var tempDateSource = this.state.dataSource;
    switch (i){
        case 0 :
            tempDateSource.MonStarNum = tempDateSource.MonStarNum + 1;
            break;
        case 1 :
            tempDateSource.TueStarNum = tempDateSource.TueStarNum + 1;
            break;
        case 2 :
            tempDateSource.WedStarNum = tempDateSource.WedStarNum + 1;
            break;
        case 3 :
            tempDateSource.ThuStarNum = tempDateSource.ThuStarNum + 1;
            break;
        case 4 :
            tempDateSource.FriStarNum = tempDateSource.FriStarNum + 1;
            break;
        case 5 :
            tempDateSource.SatStarNum = tempDateSource.SatStarNum + 1;
            break;
        case 6 :
            tempDateSource.SunStarNum = tempDateSource.SunStarNum + 1;
            break;
    }
    this.setState({
        dataSource : tempDateSource
    });
}

And this is error:

enter image description here


Source: stackoverflow-javascript