Giter Club home page Giter Club logo

react-native-loading-container's Introduction

LoadingContainer Slack

LoadingContainer is a component that co-ordinates fetching data, displaying a loading indicator while that's in progress, and an error message with a retry button when a request fails.

Why?

We are building an app where pretty much every screen has to fetch new data, so we wanted a way to generalize our logic for showing loading screens, handling errors and retries.

Installation

npm install react-native-loading-container --save

LoadingContainer is compatible with React Native 0.15 and newer.

Usage

Import LoadingContainer as a JavaScript module:

import LoadingContainer from 'react-native-loading-container';

The only two props that are required are onLoadStartAsync and onReadyAsync - these must both be async functions (or return Promises), and must resolve when they are completed.

onLoadStartAsync is responsible for fetching the data that the scene needs to render and returning it. In the example below, we return the JSON response from the reactnative subreddit. If an exception is thrown in this function, an error overlay is rendered where the user can tap to retry. Tapping retry will invoke this function again. The return value of onLoadStartAsync is fed into _onReadyAsync.

onReadyAsync is responsible for taking the data fetched by onLoadStartAsync and updating our component state. When it resolves, LoadingContainer will hide the loading indicator.

export default class ListScreen extends React.Component {

  render() {
    return (
      <LoadingContainer
        onLoadStartAsync={this._loadInitialDataAsync.bind(this)}
        onReadyAsync={this._onReadyAsync.bind(this)}>
        { /* render content */ }
      </LoadingContainer>
    );
  }

  async _loadInitialDataAsync() {
    let response = await fetchWithTimeout('https://www.reddit.com/r/reactnative.json');
    return response.json();
  }

  async _onReadyAsync({data: {children: stories}}) {
    return new Promise((resolve) => {
      this.setState({stories}, resolve);
    });
  }

}

A complete, runnable example is available in Examples/StarterTemplate.

LoadingContainer can be used anywhere, but is especially well-suited to wrapping the content of your scene components. A scene component is the top-level component for each route.

Customization

LoadingContainer was built to our specific use case so it might not have all of the hooks that you will want to customize it for your application -- if this is the case, please submit a pull request.

Currently only the following props are exposed:

  • onError - invoked with the exception object when onLoadStartAsync throws an exception.
  • renderLoadingOverlay - returns a React element that will be rendered when loading is in progress. It must implement showOverlay, hideOverlay and fadeOverlay methods.
  • renderErrorOverlay - returns a React element that will be rendered when error occurs. It will receive a function prop called onRetryLoad that should be invoked when the user indicates that they would like retry fetching data.
<LoadingContainer
  onError={e => console.log(e)}
  renderLoadingOverlay={props => <MyCustomLoadingOverlay {...props} />}
  renderErrorOverlay={props => <MyCustomErrorOverlay {...props} />}
/>

react-native-loading-container's People

Contributors

brentvatne avatar ide avatar juankiz avatar nikki93 avatar owenflood avatar samyakbhuta avatar terribleben avatar yinghang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-loading-container's Issues

Loading overlay style

It's good to have. Everybody happy with loading overlay but it would be great to have styling props for it. I'll make a PR in near future.

null is not an object (evaluating 'this._loadingOverlay.fadeOverlay')

Holla,

i get the above mentioned error sometimes. Any idea what to do or how to solve this?

My code:

    } else {
        return (
            <LoadingContainer
                onLoadStartAsync={this._loadInitialDataAsync.bind(this)}>
                { /* render content */ }
                <View style={{flex: 1}}>
                    <Image style={styles.backgroundImage}
                           source={require('../../Images/paper_background_icon.png')}/>
                    <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderNetworkList}
                    />
                    <AddNetworkActionBtn
                        style={{flex:1}}
                        navigator={this.props.navigator}
                        {...this.props}
                        actualNetworks={actualNetworks}/>
                </View>
            </LoadingContainer>
        )
    }
},


async _loadInitialDataAsync() {
    let response = await fetch(API_URL + 'families', {
        method: 'GET',
        headers: {'Authorization': AuthStore.getUserTokenWithBearer()}
    });
    return response.json();
},

React.PropTypes is deprecated

Hello, I was planning on using your component for a project, but after testing your example I get multiple yellow warnings. These warnings are generated because React.PropTypes is being manually called for the indeterminate prop on ProgressBarAndroid.

The same warning links me to https://fb.me/react-warning-dont-call-proptypes.

I tried to fix it by myself but I couldn't figure it out.

I've attached screenshots of the three warnings I get.

screenshot_20170316-182525
screenshot_20170316-182529
screenshot_20170316-182534

Launching app from pre-bundled file won't find onLoadStartAsync

Hi Brent, thanks for putting this together! It solves a problem I was about to tackle within my app.

I ran into this issue when loading my app from a pre-bundled file.
Xcode log shows this error:
'Warning: Failed propType: Required prop onLoadStartAsyncwas not specified inLoadingContainer. Check the render method of PropertyList.'
If I load the app from the development server everything works wonderfully.
Is this a bug or a noob mistake? Can you point me on the right direction please?

Versions:
react-native-loading-container: 0.2.0
react-native: 0.15.0

Snippet:

class PropertyList extends Component {
  async _loadProperties() { /* stuff */ }

  async _handleResponse() { /* more stuff */ }

  render() {
    return (
      <LoadingContainer style={styles.searchBarContainer}
        onLoadStartAsync={this._loadProperties.bind(this)}
        onReadyAsync={this._handleResponse.bind(this)}
      >
        <ListView  />
      </LoadingContainer>
    )
  }
}

How to Integrate with Pull to Refresh?

My LoadingContainer renders a ListView which contains a refreshControl prop:

<LoadingContainer
  ...
  onLoadStartAsync={this._loadInitialDataAsync.bind(this)}
  onReadyAsync={this._onReadyAsync.bind(this)}
  ...
>
  <ListView
    ...
    refreshControl={
          <RefreshControl
            ...
            onRefresh={() => {}} // what should I supply here?
            ...
          />
    ...
  />
</LoadingContainer>

What should I be supplying to onRefresh to get it to play nicely with onLoadStartAsync and onReadyAsync? I basically just want to re-execute their logic to get my ListView's data to update, but I'm not sure how to get that to work. Example would be great!

How to use with Apollo?

I've been using this library with great success for simple fetch requests to external resources, but now I'm bringing Apollo / GraphQL into my codebase and I'm wondering how to properly use it with this package.

Apollo fetches data using its own HOC. You specify the query, and the data arrives at some point

const withQuery = graphql(gql`
  {
    nativeCurrencies {
      name
      symbol
    }
  }
`);

const enhance = compose(
  withQuery,
);

export default enhance(SomeComponent);

So my logic for handing the fetch is abstracted away into Apollo's HOC, so I don't have direct control over it anymore. All I have to work with is whether or not data.loading is true or false, which is great for DX. But I start to lose control over things like this.

Is there a way to get these two systems to work together? Perhaps, passing in my loading state directly rather than specifying the async functions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.