Home > database >  Update react redux state only work on second click
Update react redux state only work on second click

Time:10-23

I am new in react-redux I want to get data on submit from Redux, if I get success true then I want to navigate to another screen otherwise an alert will show.

However, I am getting success only after second click

Code :

const {fetchLoginData} = props;
const data = props;

async function onSubmit() {

  fetchLoginData(phoneNo);

   //if i get true from fetchLoginData(phoneNo) then navigate to other screen otherwise an alert will show
   if(data.login)
      props.navigation.navigate('ScreenName')
   else
      alert("User Not Registered")
}

CodePudding user response:

I am not too sure on how your element is laid out but I am assuming that your touchable tag is not large enough. Here is an example of me giving it a height of 300 and a width of 700. You can make it as large as you need.

const GradientBtn = () => {
  return (
    <TouchableOpacity
      onPress={() => onSubmit()}
      style={{height: 300, width: 700}}>
      {/* INSERT BUTTON CODE HERE */}
    </TouchableOpacity>
  );
};

CodePudding user response:

This is due to asynchronous operation. The data.login check made immediately after the fetchLoginData() function running on the first click is incorrect for the first case. Therefore, there is no redirection with the first click. When you click again, it redirects because state is already true.

You can fix it like this: If the response is full in the fetchLoginData() function, it will be correct to redirect.

Or you can use this. You can call a redirect function anywhere in the component where the form design is. E.g;

<View>
<Form>
....
</Form>
{data.login && props.navigation.navigate('ScreenName')}
</View>
  • Related