I am fetching data from an API and displaying it. (This part is working). So to get a better overview of what I’m trying to do:
- The user presses a button to take a test.
- This will fetch alcohol and temperature from my API: which is like {"alcohol":291,"temperature":25}
- If the alcohol and temperature are above a certain threshold give a tick or a cross along with the reading
- Store this data in my Firestore as success or failure to do the test
The code:
import { StyleSheet, Text, View, ActivityIndicator, FlatList,TouchableOpacity } from 'react-native'
import React, { useEffect, useState } from 'react'
import { auth, database } from '../config/firebase';
import { collection, doc, setDoc } from 'firebase/firestore';
import { Alert } from 'react-native-web';
const url = "url";
function AlcoTestButton(){
const [isLoading,setLoading] = useState(false);
const [alcohol, setAlcohol] = useState();
const [temperature, setTemperature] = useState();
const fetchData= async ()=>{
setTimeout(function(){
setLoading(true)
fetch(url)
.then((response) => response.json())
.then((json) => {
setAlcohol(json.alcohol);
setTemperature(json.temperature);
//send to database
const sensorID = doc(collection(database, 'sensors'));
setDoc(sensorID,{
uid: auth?.currentUser?.uid,
alcohol,
temperature,
});
})
.catch((error) =>{alert(error)})
.finally(()=>{setLoading(false)});
},5000);
}
const checkToxic = () => {
if ({alcohol}>250){
console.log("ALERT")
}
}
return (
<View style={styles.container}>
<TouchableOpacity
onPress={()=>fetchData() && checkToxic()}
style={styles.button}>
<Text style={{ color: "white"}}>Take Test</Text>
</TouchableOpacity>
{isLoading && (<ActivityIndicator />)}
{!isLoading && !!temperature && !!alcohol &&
<View>
<Text>Alcohol = {alcohol}</Text>
<Text>Temperature = {temperature}</Text>
</View>
}
</View>
)
}
Any help or guidance would be much appreciated.
2
Answers
you can try like this. Please import useEffect first.
You could use useMemo like this:
Now
checkToxic
will be updated every timealcohol
changes. You can use it to conditional render a component.