Search code examples
reactjsreact-nativereact-native-iosreact-native-0.46

Component doesn't update the value after call webService in React Native


I Called the GET webService in React Native, Its get Successfully response. But I want to set this response in Component. its means according to response the component doesn't update. See my code.

GET REQUEST :

 makeRemoteRequest = () => {
   this.setState({ loading: true });
   fetch('http://jsonstub.com/ws/pendingInvoices', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'JsonStub-User-Key': 'daf0e17a-5951-49e0-8d32-4cb4bb804577',
        'JsonStub-Project-Key': '4e70b1a8-12d0-4fa5-8c34-a99b666bd073',
      }
    })
     .then(res => res.json())
     .then(res => {

       console.log('Data Is : ' ,res);
       this.setState({
         text : res,
         customData : res,
         error: res.error || null,
         loading: false,
         refreshing: false
       });
     })
     .catch(error => {
       console.log('error Is : ' ,error);
       this.setState({ error, loading: false });
     });
 };

Service Called :

 componentDidMount() {
   this.makeRemoteRequest();
 }

Want To Update text and Accordion,

render(){
       const { navigate } = this.props.navigation;
        return (
          <View style = {styles.scrollSty}>
               <Accordion
                  sections={this.state.customData}
                  renderHeader={this._renderHeader.bind(this)}
                  renderContent={this._renderContent.bind(this)}
                />
              <View><Text style = {{color : 'white'}}>{this.state.text}</Text></View>

         </View>
        );
     }
    }

Solution

  • Ya. Finally Get the solution : Here we can update the component using two ways.

    1. Forceful Update : Call the function after set the values.

        this.setState({
           customData: customData,
           ...
         });
         this.forceUpdate()
      
    2. Calling shouldComponentUpdate : if you don't call then doesn't update.

        shouldComponentUpdate(nextProps, nextState) {
          return true;
        }