Search code examples
reactjsreact-nativeapionpress

How to solve freeze of on press until another fetch api finishs in react native


In react native I notice a problem of freezing in onPress clicking event until api call is over and the data comes back.

For example if a button click just show alert message or it is navigation to another screen:

 <Button title="Click for other functionality"
              onPress={()=>{
                Alert.alert("Another click")
  }} />

And the api call is fetching data from jsonplaceholder:

  baseURL = 'https://jsonplaceholder.typicode.com';
  getData = (ev)=>{
        this.setState({loaded:false, error: null});
        let url = this.baseURL + '/photos';
        let h = new Headers();
        h.append('Authorization', 'Bearer sjdkfhakdkakhkajsdhks');
        h.append('X-Client', 'Steve and Friends');

        let req = new Request(url, {
            headers: h,
            method: 'GET'
        });

        fetch(req)
        .then(response=>response.json())
        .then(this.showData)
    }

getData and is called in componentDidMount.

The problem is when the button (Click for other functionality) is clicked it never works until getData has finished. How to make the button works without waiting the api call to finish ?

The problem never appear in ios, only in android.

The complete snippet code link


Solution

  • One does not simply create 5000 views without any lag.

    My Advice Use FlatList instead of ScrollView.

                    <FlatList data={this.state.data} renderItem={({item,index})=>{
                       return ( <Text key={item.id} style={styles.txt}>
                            {item}
                        </Text>)
                    }
                    }/>
    

    This is the way.