Hi There is a toggle in my component which will show a login method according to the value true or false
The login icon will show if true and will not if false.
The operation is carried out in the setting page.
So I make a toggle button In the setting page. I am using async storage since I wanna save data if the button opened by user or not.
Here what in the setting page
const toggleSwitch = async () => {
await AsyncStorage.setItem('enableBiometric', isEnabled.toString());
setIsEnabled(!isEnabled);
};
const printSomething = async () => {
try {
const value = await AsyncStorage.getItem('enableBiometric');
console.log(value);
} catch (err) {
console.log(err);
}
};
return (
<View>
<View style={styles.button}>
<Text>Turn on Biometric Login</Text>
<Switch
trackColor={{false: switchDefaultColor, true: primaryColor}}
thumbColor={isEnabled ? '#ffffff' : '#f4f3f4'}
ios_backgroundColor={switchDefaultColor}
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
<TouchableOpacity onPress={() => printSomething()}>
<Text>Text</Text>
{isEnabled ? <Text>Enabled</Text> : <Text>DisEnabled</Text>}
</TouchableOpacity>
</View>
)
What happens is the when the component is loaded the previous state of button state is loaded from the async storage.
But During the first 2 or 3 times of toggling switch. Only The Ui Change of <Text>Enabled</Text> or <Text>DisEnabled</Text>
. The Storage data won't change.
Eg Scenario
When component load, app get data from storage. The switch is on
. When I press printSomething button its will say on
.
When I press switch for the first time. The switch UI will go off. But when I press printSomething button its will still on
.
Its always happen.
CodePudding user response:
enableBiometric
is needs to be loaded fromAsyncStorage
first after that render uiin
toggleSwitch
function,isEnabled
value needs to be same for bothsetIsEnabled
&AsyncStorage.setItem