Search code examples
javascriptreact-nativeaxioslifecycle

React Native Loading data when button is pressed


I am interested in getting my QuestionList.js component to load data when a button is pressed, however I do not want it to load all the data from the api, just one object per screen from this array of 10 objects.

I believe I have an order of operations problem here that I need some help solving.

I do know how to fetch data from an API using axios and componentWIllMount() which will fetch my data the moment the app boots up, but I am not sure if this is what I want to do since its a quiz application.

So I only want this array of objects to be fetched when a user presses a button.

Or am I thinking about this all wrong? Should I continue on with this configuration:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';

class QuestionList extends Component {
  componentWillMount() {
    axios
      .get('https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean')
      .then(response => console.log(response));
  }

  render() {
    return (
      <View>
        <Text>Question List!!!</Text>
      </View>
    );
  }
}

export default QuestionList;

which is working and then have it load a second time when a user presses a button and then that's when it actually renders to the screen?

Should I even be using the componentWillMount() lifecycle method if the user does not need the data until a button is pressed?

Please help.


Solution

  • The user experience friendly doing things would be making the required data ready before the user requests to see it. This way user would not have to wait for data to load every time the screen changes.

    If your data is big then requesting only the next screens data is more logical. This way user won't have to wait for data to load and app will be ready sooner when it started. For example, loading first 2 items when the app loads and loading the third item when user navigates to second item, loading fourth item on third and so on.

    If your data is not big and request completes fairly quick then getting them in one go will result in less requests to server and will have more performance require less bandwitch etc..

    It is up to your apps requirement and to your decision