0

I am creating react-native app using fetch method to get the data from API but when I am build the app(remove and install new app) that time it is calling API called but on 2nd time it is not. I have also uses

componentDidMount, componentWillMount

but not work for me. following is my code:

export default test extends Component{
_isMounted = false;
constructor(props){
  super(props);
  this.state = {
      showList:[]
 }
}
componentDidMount() {
    let currentComponent = this;
     currentComponent._isMounted = true;
    fetch(API_URL, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    }).then((response) => { return response.json()})
    .then((responseJson) => {
        console.warn("responseJson: ", responseJson);
        if(currentComponent._isMounted){
         currentComponent.setState({showList: responseJson.data});
        }

    })
    .catch((error) => {
      console.error(error);
    }); 

}
componentWillUnmount(){
    this._isMounted = false
}

}

I have add full code here. this is only called on first time, after that it will get only from cache(I think).Please help me. Thanks

kachnitel
  • 450
  • 8
  • 20
Vipul Bhagwat
  • 49
  • 1
  • 7

1 Answers1

1

I'd look into the onEnter hook on your scene using react-native-router-flux.

Something like this should work:

class Test extends Component {
  static onEnter() {
    fetch(API_URL, {
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    }).then((response) => { return response.json()})
    .then((responseJson) => {
        console.warn("responseJson: ", responseJson)
        if (currentComponent._isMounted) {
         currentComponent.setState({ showList: responseJson.data })
        }

    })
    .catch((error) => {
      console.error(error)
    })
  }
}

(if you need to access this in the method, here is an idea)

kachnitel
  • 450
  • 8
  • 20