I currently have a react native app with a nodeJS backend. I using a function to get the data from the backend, then using that data to conditional render a button in my app.
My problem is that as soon as the app loads i keep getting undefined then true and hence the functionality does not work due to the undefined value. Does anyone know why that might be happening?
Here is my code:
const [data,setData]=useState([]);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [isEnabled, setIsEnabled] = useState(data.locked);
const [activated, setActivated] = useState(data.activated);
const loadData = async () => {
setLoading(true);
const response = await Api.getData();
setLoading(false);
if(refreshing)
setRefreshing(false);
if (!response.ok){
return setError(true);
}
setError(false);
setData(response.data)
if(response.data.locked===true)
setIsEnabled(true);
};
useEffect(() => {
loadData();
}, [data.locked]);
console.log(data.activated)
const activate = ()=>{
setActivated(true);
}
return(
{activated != true ?
<View style={{justifyContent:'flex-start',
alignItems:'flex-start',marginLeft:-10}}>
<Button title='Activate' onPress={activate}/>
</View>
:
null
}
)
data.activated prints out the following
undefined
undefined
undefined
undefined
true
true
true
true
true
and the button is getting displayed when it's not supposed to.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…