Selim Mıdıkoğlu
Selim Mıdıkoğlu

Reputation: 136

setState() in render function return?

this.state = {
      fontLoading: false,
      dataFetched: false,
    };

I have two states which fontloading is changing inside async componentDidMount() and dataFetched is changing inside another function. 'fontLoading' is changing in below function.

async componentDidMount () {
    try {
      await Font.loadAsync ({
       ...
      });
      this.setState ({fontLoading: true});
    } catch (error) {
      ...
    }
}

First if and else if work fine with fontLoading and dataFetched. In last else condition screen is rendered for a second, than I got an error, because I am trying to change dataFatched state when Button is clicked. Render function again renders the View inside 'else if' condition after a second. But I want to render else condition and when I click the button I have to get else if return.

render(){
    if (!this.state.fontLoading) {
      return (<ActivityIndicator />);
    }
    else if (!this.state.dataFetched) {
      return (new<View>)
    }
    else {
      return (
      <View>
        <Button title = 'Click' onPress={this.setState({dataFetched: false});}></Button>
      </View>
     );
    }

I have not a certain knowledge of setting states inside render functions. What should I do to accomplish this certain task? Learning this here will increase my learning flow because rendering inside same component with state changes both encourages how to use states and what makes react-native beautiful I suppose.

Upvotes: 0

Views: 1240

Answers (1)

Eugene Pawlik
Eugene Pawlik

Reputation: 1190

The way you have the onPress attribute written will end up calling this.setState({dataFetched: false}) right away when the component is rendered. onPress should be given a function as an argument, and that function should call setState.

onPress={this.setState({dataFetched: false});} // <- Replace this

onPress={() => this.setState({dataFetched: false})} // <- with this

Upvotes: 1

Related Questions