React-Native — Promise setup e data handling

2019-07-25 18:06发布

问题:

I am trying to understand how developers use Promise with React-Native. It would be great to get feedback and recommendations on how to setup API calls and handle the data. Please understand I never used Promise before and that I am new to React-Native.

Thank you in advance. Any resource about this subject is welcome too.

Pseudocode

Child

  • Retrieve two variables
  • Use these two variables to build an URL
  • Trigger the first Promise and resolve
  • Retrieve another two variables
  • Use these two variables to build a new an URL
  • Trigger the second Promise and resolve
  • Gather the data from both promises and pass to parent

Parent

  • Retrieve data from Child
  • Get data from the first Promise and set to a state
  • Get data from the second Promise and set to another state

APIservice.js

Child

Is it a good practice to setup all your API calls in a separate file? It's likely that in the future I will need to make different API calls, would you create multiple functions to handle that?

class APIservice {


    _getStopPoint = (endpoint) => {
        return new Promise(function(resolve, reject) {
            fetch(endpoint)
            .then((response) => response.json())
            .then((data) => {
                console.log("APIservice StopPoint", data)
                resolve(data);
            });
        });
    };
};


module.exports = new APIservice

App.js

Parent

As you can see, the way I setup the endpoint is lame. It's not ideal as the URL is the same. I want to structure something that can receive two variables and build the URL on the go. Something like https://api.tfl.gov.uk/Line/${routeid}/Arrivals/${stationid}.

If I manage that, how can I pass the API call to the APIservice having only one endpoint that dynamically will change based on the two variables it receives? I am not sure how to differentiate the call in the Promise.all having only "one" URL.

That brings me another issue. When setting the state in App.js, should I setState using the specifics array from data? Something like bus: data[0], tube: data[1]. Is this a good practice?

let APIservice = require('./APIservice')

let endpoint = 'https://api.tfl.gov.uk/Line/55/Arrivals/490004936E'
let endpoint1 = 'https://api.tfl.gov.uk/Line/Northern/Arrivals/940GZZLUODS'


let loadData = (endPoint) => {

  // Multiple API calls
  Promise.all([
    APIservice._getStopPoint(endpoint),
    APIservice._getStopPoint(endpoint1),
  ])
  .then((data) => {
    console.log("App.js", data)
  })
  .catch((error) => {
    console.log(error)
  })
}

export default class App extends Component {

  componentWillMount() {
    // URL fetch based on variables, not dynamic
    loadData(endpoint)
    loadData(endpoint1)
  }

  render() {
    loadData("hello")
    return (
      <View style={styles.container}>
        <Text>
          Promise
        </Text>
      </View>
    );
  }
}