I am trying to create a button that when i click it it will be disabled and when i reload the app it will stay disabled , until i press clear.
The problem is i have to click twice to get the result i want. Here is my code:
github.com/giannischiout/stateBtn/tree/master
import React, {useState, useEffect} from 'react';
import {
View,
TouchableOpacity,
Button,
Text,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const BtnSave = () => {
const [isChecked, setIsChecked] = useState(false);
useEffect(() => { getButtonOption() }, [])
const getButtonOption = async () => {
try {
const jsonValue = await AsyncStorage.getItem('buttonCheck', )
const value = JSON.parse(jsonValue)
setIsChecked(value);
} catch(e) {
console.log(e)
}
}
//Execute when i click the button
const buttonActions = async () => {
setIsChecked(previousValue => !previousValue)
buttonSaveClicked();
};
const buttonSaveClicked = async () => {
let btnValue = isChecked.toString();
//Have to click twice to change the value
console.log(`btn value is: ${btnValue}`)
await AsyncStorage.setItem('buttonCheck',btnValue )
};
return (
<TouchableOpacity >
<View>
<Button title='save settings' onPress={buttonActions}></Button>
</View>
</TouchableOpacity>
)
}
The problem is with the getButtonOption function, since the key does not exist yet in the asyncstorage, it returns a null. Hence your isChecked is null on the first press. A very simple fix is to check if the value that is being retrieved on first load is a null value or not. Then set the correct state from there.