user16413578
user16413578

Reputation:

How to add a preload (something like loading... or fetching...) react native axios call?

I have following code.

axios.post('/user', {
    limit: '1000',
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

It took around 1-3 seconds to get data. In the meantime, how can I display something like loading..... or fetching.....

Upvotes: 0

Views: 829

Answers (2)

Abdul Kabir
Abdul Kabir

Reputation: 128

take a state

const [loading, setLoading] = useState(false)

now in your code before the axios call

setLoading(true)
axios.post('/user', {
limit: '1000',
})
.then(function (response) {
console.log(response);
setLoading(false)
})
.catch(function (error) {
console.log(error);
setLoading(false)
});

now you can display an activity indicator or whatever you want to display when the data is loaded by checking the loading state in your code

{loading && <Text>loading...</Text>}

or

{loading && <ActivityIndicator animating />}

Upvotes: 0

Gourav Goel
Gourav Goel

Reputation: 83

if you are working with classes in react native then you can use the below implementation, let me know if you are facing any issues.


    import {ActivityIndicator } from 'react-native';

    export class YOUR_CLASS_NAME extends Component{
        constructor(props)
        {
            super(props);
            this.state ={
                isFetching:false,
            }
        }
        async componentDidMount() 
        {
                this.setState({isFetching:true});
                //fetch your data here from axios
                this.setState({isFetching:false});
        }
        
        render()
        {
          
            return(
                <View style={{flex:1}}>
                  //your text 
                  {this.state.isFetching &&
                    <ActivityIndicator animating={true} backgroundColor="#ffffff" color={'#000000'} />
                  }
                </View>
            );
        }
    }


            

Upvotes: 1

Related Questions