1

Normally when using this.setState(), the component re-renders after updating state via setState(). Unfortunately, I have this problem where the state updates but the component doesn't re-render until interacting with the component again (i.e. clicking the component again). Here's my code:

  constructor(props) {
    super(props);
    this.state = {
      value: new Date(),
      time: 0,
      displayTime: null,
      show: false,
    };
    this.showTimePicker = this.showTimePicker.bind(this);
  }

  showTimePicker() {
    console.log(this.state.show);
    this.setState({show: true}, () => console.log(this.state.show));
    //console.log to verify state changes
  }


render() {
 return(
  <View>
  //code that determines if the datetimepicker modal shows up
  {this.state.show && (
     <DateTimePicker
        value={this.state.value}
        mode="time"
        display="spinner"
        onChange={(date, value) => {
           console.log(value, 'value');
           this.setTime(value);
           setShow(this.state.show);
        }}
      />
   )}
   
   //when button is pressed this.state.show changes to true
   <Button title="Change Time" onPress={this.showTimePicker}></Button>
   </View>
);}

So what I want is for the DateTimePicker modal to show up every time the button is pressed. What happens currently though is when I press the button nothing registers (state still changes) until I click the screen again (then the modal shows up). How can I get it so that the button makes the modal pops up instantly?

Jerry Zhou
  • 43
  • 2
  • 6
  • Could you give this a try?: {this.state.show ? ( { console.log(value, 'value'); this.setTime(value); setShow(this.state.show); }} /> ) : null } – thewoodcutter May 14 '21 at 02:29
  • I just tried it, the problem still persists though. – Jerry Zhou May 14 '21 at 02:36
  • @JerryZhou can you explain what are you trying to achieve by adding `this.setTime(value); setShow(this.state.show);` in your `onChange` prop within the DateTimePicker? I don't see your complete code but with the info you shared this does not seem correct to me. – Subha May 14 '21 at 06:12
  • Sorry, that's my fault that I didn't show the setTime() function. I didn't think the code was relevant to the question. Essentially, setTime() changes a text component on the screen to show the updated time from the modal. The setShow() function is a prop that hides the modal from popping up repeatedly after getting a response from the user. As it turns out, the problem was with using the debugging mode for some reason, so turning it off makes the app work like usual. – Jerry Zhou May 14 '21 at 18:23

1 Answers1

2

I faced the same issue while I was using the app in debug mode, So can just disable the debug mode and it should work properly.

Here is the similar question : UI doesn't update until tap on the screen when setState is called inside a realm listener callback

Dipan Sharma
  • 1,114
  • 7
  • 17