Make unclickable button after fetch starts React Native

Viewed 649

I was trying to disable my button after fetch starts so they can't do multiple fetches, also when fetching finish to make it its processes make the button clickable again, do you know how to implement this?

this is my code:

import React from 'react';
import { StyleSheet, Text, View, Button, ActivityIndicator } from 'react-native';


export default function App() {

  const [nombre,setNombre]= React.useState('');
  const [isLoading,setIsLoading]= React.useState(false);
  

  const fetchDatos = async () => {
    setIsLoading(true);
    return fetch('http://localhost:8000/api/consulta', {method: 'POST', headers: new Headers({'Accept': 'application/json',
         'Content-Type': 'application/json',

       }),       body: JSON.stringify({
         codigoParticipante: '1520',
         contrato: '135927',
      })}).then(response => {
      return response.json();
})
  .then(responseJson => {

  
      setIsLoading(false);
      setNombre(responseJson.Participante.InfoParticipante['@attributes'].Nombre);
  }}).catch(function() {
    alert("Sorry, server offline");
  });
} 
  
  return (
    <View>
    <Button 
      title='press me'
      onPress={fetchDatos}
    />
    <Text>{nombre}</Text>
    {isLoading && (
        <ActivityIndicator
            style={[{height: 80}]}
            color="#C00"
            size="large"
            hidesWhenStopped={true}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

any suggestion I would appreciate it a lot!

1 Answers

Disable the button while fetching

 <Button 
  title='press me'
  onPress={fetchDatos}
  disabled = {isLoading}
/>
Related